【问题标题】:NodeJS: Real time client notification about last upload timeNodeJS:关于上次上传时间的实时客户端通知
【发布时间】:2019-11-01 18:34:49
【问题描述】:

用户可以通过我的 /upload HTTP 端点上传数据 (我使用 NodeJS/Express 对其进行编码)。 我需要实时更新网页(ReactJS)以显示上次上传时间。 我尝试为此使用 SSE 并解决了问题。

这是将数据上传到服务器的工作代码:

 const upload = async (req, res) => {
    try {
       // upload logic is here ..
    return res
      .status(200)
      .send('Success!');

  } catch (e) {
    return res.status(500).send(e.message);
  }
};

为了使用上次上传的时间戳实时更新网页,我尝试在 return 语句之前的 try{} 块内将以下 SSE 函数注入到上面的 upload() 函数中:

function sendSSE(response) {
  response.writeHead(200, {
    Connection: 'keep-alive',
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Access-Control-Allow-Origin': '*',
  });

  const content = JSON.stringify(Date.now());
  response.write(content);
  response.write('\n\n');

}

我得到了错误:

错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头

【问题讨论】:

标签: node.js express


【解决方案1】:

您不能两次发送标头。

当您调用res.status(200)response.writeHead(200, ...) 时,您将强制输出状态行和标题。这不是你能做的。

简单地说,不要那样做。摆脱你的res.status(200).send('Success!'); 位。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多