如何在Node.js搭建的本地服务器中正常加载带CSS样式的HTML文件
问题原因
你当前的Node.js服务逻辑是所有请求都统一返回index.html文件,当浏览器解析到HTML里的CSS引入标签时,会主动向服务端发起/css/desktop.css路径的请求,但此时你返回的依然是HTML内容,Content-Type也还是text/html,浏览器无法识别为CSS样式,所以不生效。
修复后的代码示例
const http = require('http'); const fs = require('fs'); const path = require('path'); http.createServer(function(req, res) { // 处理默认访问路径 let filePath = req.url === '/' ? 'index.html' : `.${req.url}`; // 根据文件后缀匹配对应的Content-Type const extname = path.extname(filePath); let contentType = 'text/html'; switch (extname) { case '.css': contentType = 'text/css'; break; case '.js': contentType = 'text/javascript'; break; case '.png': contentType = 'image/png'; break; case '.jpg': contentType = 'image/jpeg'; break; } // 读取对应路径的文件返回 fs.readFile(filePath, (error, data) => { if (error) { res.writeHead(404); res.end('404 Not Found'); return; } res.writeHead(200, { 'Content-Type': contentType }); res.write(data); res.end(); }) }).listen(8080);
注意事项
- 确保css文件夹、index.html、服务启动脚本在同一级目录,路径对应正确
- 后续如果需要支持其他静态资源,直接在上述switch代码块中补充对应文件后缀和Content-Type即可
内容的提问来源于stack exchange,提问作者Vivek
相关产品推荐
相关产品推荐

