NodeJS HTTP服务器异常:仅关闭服务时页面才加载显示
Node.js Web服务器页面持续加载的解决办法
你的问题核心是没有调用res.end()方法结束HTTP响应:代码里只写了res.end,这只是对函数的引用,没有执行它。浏览器会一直等待服务器发送响应结束的信号,直到服务器关闭才会渲染内容。
修改后的代码
const http = require("http") const port = 8080 const fs = require("fs") const server = http.createServer(function (req, res) { fs.readFile("index.html", function (error, data) { if (error) { res.writeHead(404, { "Content-Type": "text/plain" }) res.write("Error") } else { res.writeHead(200, { "Content-Type": "text/html" }) res.write(data) } // 调用res.end()结束响应,让浏览器停止加载并渲染内容 res.end() }) }) server.listen(port, function (error) { if (error) { console.log("Something went wrong") } else { console.log("Server is listening on port " + port) } })
关键修改说明
- 必须调用
res.end():这是结束HTTP响应的关键步骤,没有它服务器不会告诉浏览器“内容已发送完毕”,浏览器会一直处于加载状态。 - 调整状态码发送位置:避免先发送200状态码后又发送404,因为HTTP响应头只能发送一次,重复调用
res.writeHead会触发错误。
如果是直接返回文本的场景,同样要确保调用res.end():
const server = http.createServer(function (req, res) { res.writeHead(200, { "Content-Type": "text/plain" }) res.write("hey") res.end() // 不能省略这一步 })
内容的提问来源于stack exchange,提问作者Deonisos69
相关产品推荐
相关产品推荐

