【问题标题】:NODEJS - Can't set headers after they are sentNODEJS - 发送后无法设置标题
【发布时间】:2016-04-03 21:43:00
【问题描述】:

我有一个函数,当 'dataCompiled' 事件触发时执行,它看起来像他的:

eventEmitter.on('dataCompiled', function () {
        json = JSON.stringify({
          conversations: convs
        });
        res.json(json).end();
        return;
      });

但是当我刷新页面时,我得到了错误

Error: Can't set headers after they are sent.

【问题讨论】:

    标签: node.js http events callback header


    【解决方案1】:

    终于想通了,需要直接发送json到end函数,所以会是这样的:

    res.end(json);
    

    【讨论】:

      【解决方案2】:

      如果我没记错的话,你不需要字符串化和结束对 res.json 的调用:

      eventEmitter.on('dataCompiled', function () {
          return res.json({
              conversations: convs
          });
      });
      

      【讨论】:

        【解决方案3】:

        您确定在本次通话后不会发送更多数据吗?你不应该使用res.end():http://expressjs.com/en/4x/api.html#res.end

        如果您的代码中有其他地方您正在向 res 发送更多数据,它将给出您收到的错误消息, res.end 没有解决根本问题。

        【讨论】:

        • 不,这是我唯一打电话给res的地方
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-22
        • 2015-12-20
        • 2016-09-25
        • 1970-01-01
        相关资源
        最近更新 更多