Express.js-如何检查标头是否已发送? [英] Express.js - How to check if headers have already been sent?

查看:87
本文介绍了Express.js-如何检查标头是否已发送?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a library which may set headers. I want to give a custom error message if headers have already been 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 been sent?

推荐答案

从express 4.x开始,您需要使用res.headersSent.还要注意,您可能需要在检查之前使用setTimeout,因为在调用res.send()之后,它不会立即设置为true. 来源

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

简单:Connect的Response类提供一个公共属性"headerSent".

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

res.headerSent是一个布尔值,指示标头是否已发送到客户端.

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

从源代码开始:

/**
   * 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

这篇关于Express.js-如何检查标头是否已发送?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆