Express.js无法提供本地JavaScript静态文件问题求助
问题解决:Express无法提供静态JavaScript文件
问题根源
你的代码存在两个关键问题:
- 未引入
path模块:代码中使用了path.join()但未提前引入Node.js的path核心模块,虽然服务器控制台输出了路径,但需确保该模块被正确声明。 - 静态文件引用路径错误:
express.static已将public设为静态资源根目录,客户端访问时无需在URL中包含public前缀,但你在index.html中用了../public/JS/client.js,导致浏览器请求错误路径。
修正步骤
1. 完善index.js代码
补充path模块引入,同时规范文件路径写法:
const express = require('express'); const path = require('path'); // 新增:引入path模块 const app = express(); const http = require('http'); const server = http.createServer(app); console.log(path.join(__dirname,'/public')); app.use(express.static(path.join(__dirname,'/public'))); app.get('/', (req, res) => { res.sendFile(path.join(__dirname, '/public/index.html')); // 用path.join替代字符串拼接 }); server.listen(3000, () => { console.log('listening on *:3000'); });
2. 修正index.html中的脚本路径
去掉public前缀,直接使用静态根目录下的相对路径:
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script defer src="/JS/client.js"></script> <!-- 修正路径 --> </head> <body> done.. </body> </html>
原理说明
express.static(path.join(__dirname,'/public'))会把public目录下的文件暴露在网站根路径(http://localhost:3000/)下,因此public/JS/client.js对应的访问URL是http://localhost:3000/JS/client.js。错误的../public/JS/client.js会让浏览器请求不存在的http://localhost:3000/public/JS/client.js,触发404;服务器返回404时默认返回HTML内容,进而导致MIME类型不匹配的警告。
内容的提问来源于stack exchange,提问作者No Name
相关产品推荐
相关产品推荐

