You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:24:03