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

不使用Express.js如何通过Node.js展示CSS与图片静态资源

故障根因

当前服务逻辑对所有请求统一返回text/html类型的index.html内容,请求CSS、图片等静态资源时,返回内容与响应头类型均不匹配,导致资源加载失败。同时你在img标签中填写的资源地址端口为8888,与服务监听的8000端口不一致,也是资源加载失败的原因之一。

修复方案
  • 调整HTML内的静态资源路径:将<img class="logo" src="http://localhost:8888/pic.png" alt="My_Logo" />改为<img class="logo" src="pic.png" alt="My_Logo" />,确保styles.css、pic.png、pic1.png都和index.html存放在项目根目录下
  • 改写Node服务逻辑,根据请求资源的后缀返回对应内容与响应头
修复后完整服务代码
var http = require("http"); 
var fs = require('fs');
var path = require('path');

// 配置后缀对应的Content-Type映射
const mimeMap = {
  '.html': 'text/html',
  '.css': 'text/css',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.js': 'text/javascript'
};

function onRequest(request,response){
    let requestPath = '.' + request.url;
    // 根路径默认返回index.html
    if (requestPath === './') {
        requestPath = './index.html';
    }
    // 获取请求文件后缀
    const fileExt = String(path.extname(requestPath)).toLowerCase();
    const contentType = mimeMap[fileExt] || 'application/octet-stream';

    fs.readFile(requestPath, function(error, data){
        if(error){
            if(error.code === 'ENOENT'){
                response.writeHead(404, {'Content-Type': 'text/html'});
                response.write('404 文件不存在');
            }else{
                response.writeHead(500);
                response.write('服务器错误:' + error.code);
            }
            response.end();
        }else{
            response.writeHead(200, {'Content-Type': contentType});
            response.write(data);
            response.end();
        }
    });
}
http.createServer(onRequest).listen(8000);
console.log('服务启动成功,访问地址:http://localhost:8000');

启动服务后访问上述地址即可正常加载所有静态资源。

内容的提问来源于stack exchange,提问作者Mahir Miah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:36:04