Javascript Express.js - 如何检查标头是否已发送?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12030107/
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
Express.js - How to check if headers have already sent?
提问by powerboy
I am writing a library which may set headers. I want to give a custom error message if headers have already sent, instead of just letting it fail with the "Can't set headers after they are sent" message given by Node.js. So how to check if headers have already sent?
我正在编写一个可以设置标题的库。如果标头已经发送,我想给出自定义错误消息,而不是仅仅让它失败并显示 Node.js 给出的“发送后无法设置标头”消息。那么如何检查headers是否已经发送呢?
采纳答案by Niko
EDIT: as of express 4.x, you need to use res.headersSent. Note also that you may want to use setTimeout before checking, as it isn't set to true immediately following a call to res.send(). Source
编辑:从 express 4.x 开始,您需要使用 res.headersSent。另请注意,您可能希望在检查之前使用 setTimeout,因为它不会在调用 res.send() 后立即设置为 true。来源
Simple: Connect's Response class provides a public property "headerSent".
简单:Connect 的 Response 类提供了一个公共属性“headerSent”。
res.headerSent
is a boolean value that indicates whether the headers have already been sent to the client.
res.headerSent
是一个布尔值,指示标头是否已经发送到客户端。
From the source code:
从源代码:
/**
* Provide a public "header sent" flag
* until node does.
*
* @return {Boolean}
* @api public
*/
res.__defineGetter__('headerSent', function(){
return this._header;
});
https://github.com/senchalabs/connect/blob/master/lib/patch.js#L22
https://github.com/senchalabs/connect/blob/master/lib/patch.js#L22
回答by Willem Mulder
Node supports the res.headersSent
these days, so you could/should use that. It is a read-only boolean indicating whether the headers have already been sent.
Node 支持res.headersSent
这些天,所以你可以/应该使用它。它是一个只读布尔值,指示是否已发送标头。
if(res.headersSent) { ... }
See http://nodejs.org/api/http.html#http_response_headerssent
见http://nodejs.org/api/http.html#http_response_headerssent
Note: this is the preferred way of doing it, compared to the older Connect 'headerSent' property that Niko mentions.
注意:与 Niko 提到的旧版 Connect 'headerSent' 属性相比,这是首选方法。
回答by Manohar Reddy Poreddy
Others answers point to Node.js or Github websites.
其他答案指向 Node.js 或 Github 网站。
Below is from Expressjs website: https://expressjs.com/en/api.html#res.headersSent
以下来自 Expressjs 网站:https://expressjs.com/en/api.html#res.headersSent
app.get('/', function (req, res) {
console.log(res.headersSent); // false
res.send('OK');
console.log(res.headersSent); // true
});