必须使用 node.js 在 express 中调用 res.end() 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20355136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:25:17  来源:igfitidea点击:

Must res.end() be called in express with node.js?

node.jsexpress

提问by greuze

I have several Expressapplications, and I see that in some modules, res.end()is called at the end of a request handler (after res.sendor res.json), while in others, it isn't called.

我有几个Express应用程序,我看到在某些模块中,res.end()在请求处理程序的末尾(之后res.sendres.json)被调用,而在其他模块中,它没有被调用。

For example:

例如:

app.get('/test', function(req, res) {
    res.send('Test', 200);
});

or:

或者:

app.get('/test', function(req, res) {
    res.send('Test', 200);
    res.end();
});

Both cases work, but I'm afraid about leaks or running out file descriptors or something like that, when I run many requests. Which one is "more correct"?

这两种情况都有效,但是当我运行许多请求时,我担心泄漏或耗尽文件描述符或类似的东西。哪个更“正确”?

回答by JayQuerie.com

The answer to your question is no. You don't have to call res.end()if you call res.send(). res.send()calls res.end()for you.

你的问题的答案是否定的。res.end()如果你打电话,你不必打电话res.send()res.send()呼唤res.end()你。

Taken from /lib/response.js, here is the end of the res.send()function:

取自/lib/response.js,这是res.send()函数的结尾:

  //. . .
  // respond
  this.end(head ? null : body);
  return this;
}

回答by Konstantin Adamov

one example where you must call end() function is when you send buffer as a file to download.

必须调用 end() 函数的一个示例是将缓冲区作为文件发送以供下载。

res.write(buffer);
res.end();

回答by Adiii

res.end([data] [, encoding])

res.end([data] [, encoding])

Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.Use to quickly end the response without any data.

结束响应过程。这个方法其实来自于Node core,特别是response.end() method of http.ServerResponse.用于在没有任何数据的情况下快速结束响应。

If you need to respond with data, instead use methods such as res.send() and res.json().

如果您需要使用数据进行响应,请改用诸如 res.send() and res.json().