Node.js服务器报错:JS模块脚本MIME类型不匹配问题求助
问题根源
你的Node.js服务器存在核心问题:无论浏览器请求什么资源(比如myscript.js、style.css),服务器都只会返回index.html文件,并且强制设置Content-Type为text/html。当浏览器请求myscript.js(声明为module类型)时,它期望服务器返回application/javascript类型的内容,但实际收到的是HTML文件,因此触发了MIME类型校验错误。
修复方案
修改服务器代码,让它根据请求路径返回对应文件,并设置正确的Content-Type:
const http = require("http"); const fs = require("fs"); const path = require("path"); // 定义常见文件对应的MIME类型映射 const mimeTypes = { ".html": "text/html", ".js": "application/javascript", ".css": "text/css", ".json": "application/json", ".png": "image/png", ".jpg": "image/jpeg", ".gif": "image/gif", ".svg": "image/svg+xml" }; const server = http .createServer((req, res) => { // 处理根路径请求,默认返回index.html;其他路径返回对应文件 let filePath = req.url === "/" ? path.join(__dirname, "index.html") : path.join(__dirname, req.url); // 获取文件扩展名并转小写 const extname = String(path.extname(filePath)).toLowerCase(); // 根据扩展名匹配MIME类型,默认用二进制流类型 const contentType = mimeTypes[extname] || "application/octet-stream"; fs.readFile(filePath, (err, data) => { if (err) { if (err.code === "ENOENT") { // 文件不存在时返回404提示 res.writeHead(404, { "Content-Type": "text/plain" }); res.end("404 - 文件不存在"); } else { // 服务器内部错误返回500提示 res.writeHead(500, { "Content-Type": "text/plain" }); res.end(`服务器错误: ${err.code}`); } } else { // 返回正确的文件内容与对应Content-Type res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "no-cache, no-store, must-revalidate", Pragma: "no-cache", Expires: 0 }); res.end(data, "utf-8"); } }); }) .listen(8000, () => { console.log(`Server is running at http://localhost:8000/`); }) .on("error", (err) => { console.error("Server error:", err); });
关键修改说明
- 引入
path模块:安全解析文件路径,避免手动拼接路径出现错误 - 动态匹配请求资源:根路径返回index.html,其他路径直接映射到对应文件
- MIME类型映射:根据文件扩展名设置正确的响应类型,确保JS模块、CSS等资源被浏览器正确识别
- 细化错误处理:区分文件不存在和服务器内部错误,便于调试定位问题
修改后,浏览器请求myscript.js时会收到正确的JS文件,且Content-Type为application/javascript,MIME类型错误即可解决。
内容的提问来源于stack exchange,提问作者voiles
相关产品推荐
相关产品推荐

