[英]NodeJS Can only connect when Server is shutdown
我尝试使用以下代码使用 nodeJS 设置网络服务器:
const http = require("http")
const port = 8080
const fs = require("fs")
const server = http.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/html" })
fs.readFile("index.html", function (error, data) {
if (error) {
res.writeHead(404)
res.write("Error")
} else {
res.write(data)
}
res.end
})
})
server.listen(port, function (error) {
if (error) {
console.log("Something went wrong")
} else {
console.log("Server is listening on port " + port)
}
})
但是,当我使用 localhost 或 127.0.0.1 在任何浏览器(尝试过 chrome 和 mozilla)上连接时,页面只会在我关闭服务器时显示。 它一直在加载,直到我用 ctrl + C 关闭时才显示任何内容。 然后它将显示我的 HTML 页面。 同样的问题是当我没有使用 html 页面而只是回应
res.write("hey")
res.end
是一个 function,试试res.end()
您从未结束请求,因此浏览器一直在等待它结束,并且仅在您关闭服务器时才发生。
因为你只是展示方法
res.end
但不运行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.