[英]ERR_HTTP_HEADERS_SENT when sending progressbar update (node.js/express)
I'm trying to make a progress bar to monitor a Tesseract.recognize() call but when I try sending an update to change the progress bar I get this error:我正在尝试制作一个进度条来监视 Tesseract.recognize() 调用,但是当我尝试发送更新以更改进度条时,我收到此错误:
[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
This is what's running in the routes.js file:这是在 routes.js 文件中运行的内容:
Tesseract.recognize(
'/app/'+statistic.path_out_new
,'eng'
, { logger: m => {
console.log(m);
res.render('pages/uploadPicture.ejs', {
user : req.user
,progress : m
});
} }
)
.then(({ data: { text } }) => {
res.render('pages/uploadPage.ejs', {
user : req.user
,progress : text
});
});
Here is the relevant part of the HTML from the EJS template, uploadPage.ejs:这是来自 EJS 模板 uploadPage.ejs 的 HTML 的相关部分:
<section><div></div><progress value="<%=progress.progress%>" text="<%=progress.status%>" /></section>
I have read this question and I think the problem is caused by sending multiple headers every time there is an update to the progress bar, but how do I send information about how the function is progressing to the user (so that the progress bar updates) without sending a header, too?我已经阅读了这个问题,我认为问题是由于每次进度条有更新时发送多个标题引起的,但是我如何向用户发送有关 function 进展情况的信息(以便进度条更新)也没有发送 header? I tried res.write() as suggested here but that let to the progress bar page timing out, not updating.
我按照这里的建议尝试了 res.write() ,但这让进度条页面超时,而不是更新。
You can't only through res
: res.render
purpose is to send all the result at once and then close the HTTP request (connection could be kept open for keep alive).你不能只通过
res
: res.render
目的是一次发送所有结果,然后关闭 HTTP 请求(连接可以保持打开以保持活动状态)。 The best choice to show the progress of a job is a WebSocket.显示作业进度的最佳选择是 WebSocket。
A little improved version of your code, without using WebSockets could be:在不使用 WebSockets 的情况下,您的代码的一点改进版本可能是:
var status = {}
app.get("/update/:id", (req, res) => res.json(status[req.params.id]));
app.get("/tesseract", (req, res) => {
const id = ... ; // here generate a unique job id
Tesseract.recognize('/app/'+statistic.path_out_new, 'eng', { logger: m => {
// here update status[id] reflecting the progress
}}).then(data => {
// here update status[id] reflecting the end of the job
});
res.render("pages/uploadPage.ejs", { id, user: req.user });
});
The page rendered should call (under a setTimeout) /update/${id}
in ajax to get the updated status util it represents a job completed status.呈现的页面应在 ajax 中调用(在 setTimeout 下)
/update/${id}
以获取更新的状态,它表示作业完成状态。
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.