【发布时间】: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]:发送到客户端后无法设置标头
【问题讨论】:
-
您可能需要考虑使用an existing library 来封装您的 SSE 调用