Node.js HTTP服务路由异常:二次返回首页提示无法访问站点
问题描述
首次访问首页或联系页一切正常,但按「首页→联系页→返回首页」的路径操作时,站点提示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
相关产品推荐
相关产品推荐

