nodejs - 为什么我的异步函数运行两次

nodejs - why does my async function run twice?

本文关键字:两次 运行 函数 为什么 我的 异步 nodejs      更新时间:2023-09-26

我是node的新手.js并从在线教程中学习。我正在尝试以下代码:

var http = require("http");
// create a server
http.createServer(function(req, res) {
    console.log("Received Request");
    res.writeHead(200, {'Content-Type':'application/json'});
    res.end("{'status':'200', 'message':'Hello World'}");
    console.log("Response Sent");
}).listen(process.env.PORT, process.env.IP);

我确实收到了正确的响应,但在控制台中输出是:

Received Request
Response Sent
Received Request
Response Sent

我想知道为什么我的代码运行了两次?我犯了什么错误吗?请帮忙!!

最好的调试方法是检查网址

var http = require("http");
// create a server
http.createServer(function(req, res) {
    console.log(req.url);//add this line, I hope it will help
    console.log("Received Request");
    res.writeHead(200, {'Content-Type':'application/json'});
    res.end("{'status':'200', 'message':'Hello World'}");
    console.log("Response Sent");
}).listen(process.env.PORT, process.env.IP);

此外,正如巴萨姆·鲁巴耶(Bassam Rubaye)指出的那样,很可能是由于您案例中的图标

当您使用浏览器访问网址时,浏览器将发送对网站图标的请求,然后发送另一个内容请求,这就是您看到两个请求的原因!

使用PostMan并请求相同的URL,您应该只看到一个请求。

没有错 - 这是正常的!您的浏览器发出多个请求。nodejs也有类似的答案 - http.createServer似乎调用了两次。

希望你学习节点.js玩得开心!