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

使用Node.js在localhost托管网页时404.html无法正常弹出问题求助

静态文件服务404页不加载问题修复方案

这类问题的核心原因是请求路径匹配失败后,服务端没有正确返回public目录下的404.html文件,常见错误点和修复步骤如下:

核心修复步骤

  • 第一步:先确认404.html文件确实存放在public文件夹根目录,而非嵌套在其他子文件夹内
  • 第二步:修改Node服务的请求处理逻辑,在静态资源匹配失败的分支下,手动读取返回404文件:
    1. 先引入fs和path模块(已引入可跳过)
    2. 当静态资源路径不存在、读取报错时,设置响应状态码为404,设置响应头Content-Type为text/html,再读取public/404.html的内容返回即可
  • 第三步:调整路由判断顺序,确保404逻辑放在所有正常路由匹配的最后执行,避免被其他逻辑拦截

可参考的代码逻辑

你可以对照下面的逻辑调整现有代码:

const http = require('http');
const fs = require('fs');
const path = require('path');
// 拼接public文件夹的绝对路径,避免相对路径寻址错误
const PUBLIC_DIR = path.join(__dirname, 'public');

const server = http.createServer((req, res) => {
  // 拼接请求资源的完整路径,默认根路径返回index.html
  let filePath = path.join(PUBLIC_DIR, req.url === '/' ? 'index.html' : req.url);
  const extname = path.extname(filePath);
  let contentType = 'text/html';
  // 根据文件后缀匹配MIME类型
  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, (err, content) => {
    if (err) {
      // 请求的资源不存在时返回404页
      if (err.code === 'ENOENT') {
        fs.readFile(path.join(PUBLIC_DIR, '404.html'), (err404, content404) => {
          res.writeHead(404, { 'Content-Type': 'text/html' });
          res.end(content404, 'utf8');
        });
      } else {
        // 其他服务端错误返回500
        res.writeHead(500);
        res.end(`Server Error: ${err.code}`);
      }
    } else {
      // 资源存在时正常返回
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf8');
    }
  });
});

server.listen(3000, () => console.log('Server running on port 3000'));

验证方法

修改完成后重启Node服务,输入任意不存在的路径比如localhost:3000/test404,即可看到404.html的内容,同时浏览器控制台可以看到响应状态码为404,符合HTTP规范。

内容的提问来源于stack exchange,提问作者Aarush Paul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:09:02