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

Node.js HTTP服务路由异常:二次返回首页提示无法访问站点

问题描述

首次访问首页或联系页一切正常,但按「首页→联系页→返回首页」的路径操作时,站点提示404无法访问。

相关截图

终端请求日志
404错误页面

问题代码

var http = require("http");

http
  .createServer(function (req, res) {
    console.log(req.url);
    const url = req.url;

    if (url === "/") {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.write("<h1 style = color:red>this is home</h1> <p>marzzuk</p>");
      res.end();
    }

    if (url === "/contact") {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.write("<h1 style = color:red>this is contact</h1>");
      res.end();
    } else {
      res.writeHead(404, { "Content-Type": "text/html" });
      res.write("<h1 style = color:red>404</h1>");
      res.end();
    }
  })
  .listen(8080);

问题原因

代码逻辑存在漏洞:

  • 访问首页/时,第一个if执行res.end()后,代码不会停止,会继续执行后续的第二个if判断
  • 此时url === "/contact"不成立,会进入else分支返回404。但之前已经调用过res.end(),重复调用会导致响应异常,最终表现为返回404错误

修复方案

将第二个if改为else if,让路由判断形成互斥逻辑,确保每个请求只会匹配一个分支:

修复后的代码

var http = require("http");

http
  .createServer(function (req, res) {
    console.log(req.url);
    const url = req.url;

    if (url === "/") {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.write("<h1 style = color:red>this is home</h1> <p>marzzuk</p>");
      res.end();
    } else if (url === "/contact") {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.write("<h1 style = color:red>this is contact</h1>");
      res.end();
    } else {
      res.writeHead(404, { "Content-Type": "text/html" });
      res.write("<h1 style = color:red>404</h1>");
      res.end();
    }
  })
  .listen(8080);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:14:58