Express.js-如何检查头是否已经发送?

我正在写一个可以设置标题的库。如果已经发送了头文件,我想给出一个自定义错误消息,而不是让它失败,Node.js 给出的消息是“在发送头文件后不能设置它们”。那么如何检查头是否已经发送?

48270 次浏览

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

Simple: Connect's Response class provides a public property "headerSent".

res.headerSent is a boolean value that indicates whether the headers have already been sent to the client.

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

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.

if(res.headersSent) { ... }

See 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.

Others answers point to Node.js or Github websites.

Below is from Expressjs website: 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
});