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

首次搭建Node.js服务器展示HTML遇状态码错误,求排查解决

Node.js服务器展示HTML内容报错的解决方法

核心错误分析

  • 响应头拼写错误:代码里的"Contet-type"少了一个字母n,正确应为"Content-Type",拼写错误会导致浏览器无法正确识别返回内容的类型。
  • 误用res.writeHead方法:读取HTML文件成功后,你调用了res.writeHead(data),但writeHead的第一个参数要求是HTTP状态码(如200、404),你把读取到的HTML内容传入,Node.js会将其解析为状态码,直接触发ERR_HTTP_INVALID_STATUS_CODE错误。正确发送内容应该用res.write(data)。
  • 冗余的响应头设置:一开始就调用了res.writeHead(200, ...),但错误分支又重复设置404响应头,虽然Node.js会覆盖,但更合理的是根据请求结果单独设置一次。

修正后的完整代码

const http = require("http");
const fs = require("fs");
const port = 8020;

const server = http.createServer((req, res) => {
  fs.readFile("index.html", (err, data) => {
    if (err) {
      res.writeHead(404, { "Content-Type": "text/plain" });
      res.write("Error file not found");
      res.end();
      return;
    }
    res.writeHead(200, { "Content-Type": "text/html" });
    res.write(data);
    res.end();
  });
});

server.listen(port, function (err) {
  if (err) {
    console.log("Something went wrong");
  } else {
    console.log("server listening on port " + port);
  }
});

额外注意事项

  • 确认index.html文件和index.js在同一目录下,若不在同一目录,需填写完整的文件路径(如./public/index.html或绝对路径)。
  • 重启服务器后,访问localhost:8020即可看到HTML页面内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:40:32