【问题标题】:return response.end doesn't work as expected in node.js返回 response.end 在 node.js 中无法按预期工作
【发布时间】:2019-04-11 06:04:43
【问题描述】:

return res.end() 不会从 createServer 方法返回。此外,输出会打印两次。

虽然我不做任何 res.write 而是 console.log(..) 后跟 return only,但一切正常。只有在我尝试使用 res.write(..) 向客户端发送响应并返回 res.end() 之后,才会返回 stmt 无法按预期工作。

const http=require('http');
const server=http.createServer((req,res)=>{
                  if(req.url==='/more'){
                    console.log('Inside /more');
                    res.write("Inside /more");
                    return res.end();

                   }

                  if(req.url==='/message'){
                    console.log('Inside /message');
                    res.write("Inside /message");
                    res.end();
                    return;
                    }

                  console.log("Outside All");
                  res.write("Outside All");
                  res.end();
               });

server.listen(5000);

带有 url: "http://localhost:5000/more" 控制台输出是:Inside /more
全部外部
浏览器输出为:内部 /more

我希望控制台输出为:仅限内部 /more。第一个 'if' 之外的任何代码都不应像包含 return res.end() 一样执行。

带有 url:"http://localhost:5000/xyz" 控制台输出是:Outside All
全部外
浏览器输出为:全部外

不知道为什么 Outside All 在控制台中打印了两次。

【问题讨论】:

  • 你为什么不用快递?
  • Rahul....只是想了解原始 node.js

标签: node.js


【解决方案1】:

一切正常,如您所愿。这是因为浏览器行为对favicon.ico 进行了第二次请求。例如,如果您通过邮递员提出此请求,则将只有一个控制台日志。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2013-12-23
    • 2014-12-09
    • 2016-01-13
    相关资源
    最近更新 更多