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

如何通过http.createServer回调加载HTML页面及关联的外部CSS文件

问题根源

当前服务逻辑没有区分请求路径,无论客户端请求HTML还是CSS资源,都会统一返回index.html的内容,且响应头固定为text/html,浏览器拿到错误类型的内容自然无法解析为可用样式。

实现方案

核心逻辑是根据请求路径返回对应资源,同时匹配正确的响应头类型,代码实现如下:

const http = require('http');
const fs = require('fs');
const path = require('path');
const port = 3000;

const server = http.createServer(function (req, res) {
  // 映射请求路径到本地public目录下的文件
  let filePath = req.url === '/' ? '/public/index.html' : `/public${req.url}`;
  const fullPath = __dirname + filePath;
  // 根据文件后缀设置正确的Content-Type
  const extname = path.extname(fullPath);
  let contentType = 'text/html';
  switch (extname) {
    case '.css':
      contentType = 'text/css';
      break;
    case '.js':
      contentType = 'text/javascript';
      break;
    // 后续有其他静态资源需求可以在此补充对应配置
  }
  // 读取目标文件返回
  fs.readFile(fullPath, (err, data) => {
    if (err) {
      res.writeHead(404);
      res.end('Resource Not Found');
      return;
    }
    res.writeHead(200, { 'Content-Type': contentType });
    res.end(data);
  })
}).listen(port);

HTML文件内正常添加link标签引入CSS即可,无需额外修改逻辑:

<head>
  <link rel="stylesheet" href="./style1.css">
  <link rel="stylesheet" href="./style2.css">
</head>

需保证两个CSS文件都放在项目根目录下的public文件夹中,和index.html同级。

内容的提问来源于stack exchange,提问作者Vijay Shastri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:54:03