Node.js进度指示器反馈 [英] Node.js progress indicator feedback
问题描述
我对使用Node.js'请求'发送的进度有疑问。我有一个Node.js应用程序充当代理,实际上将一个主体转发到另一个服务器。我希望看到此上传操作的进度。现在我这样做:
I have a question about the progress of sending with Node.js 'request'. I have a Node.js application that acts as a proxy, actually forwarding a body to another server. I want to see the progress of this upload action. Now I am doing this:
BROWSER
-> UPLOAD TO NODE
-> UPLOAD TO 3rd PARTY SERVICE
-> RETURN 3rd PARTY RESPONSE TO BROWSER
如果可以的话,我会记录它以检查控制台。记录已完成的进度。但是,是否也可以返回
If this is possible, I would log it to check in the console.log how much progress is done. But, would it also be possible to return a
res.send(progress)
同时等待上传完成并发回客户端上传成功了吗?
in the mean time, while waiting for the upload to finish and send the client back the upload has succeeded?
BROWSER
-> UPLOAD TO NODE
-> UPLOAD TO 3rd PARTY SERVICE
-> RETURN progress <-
-> RETURN progress <-
...etc.
-> RETURN 3rd PARTY RESPONSE TO BROWSER
这是上传代码(非常简单)。
This is the upload code (pretty much straightforward).
var requestOptions = {
timeout: 120000,
url: url, //URL to hit
method: 'post',
headers: headers,
body: payload //Set the body as a string
};
request(requestOptions, function (error, response, body) {
if (error) {
res.send(error);
}
else {
//res.sendStatus(response.statusCode);
console.log("[RETURNING RESPONSE BODY]");
res.send(body);
}
});
推荐答案
您的问题包含两部分。一个是从请求中获取进度,可以在此处找到:上传进度 - 请求
Your question contains two parts. One is for getting the progress from request, which can be found here: Upload Progress — Request
另一部分是通知浏览器进度。 HTTP协议不允许您发送多个响应,因此无法使用 res.send(progress)
。
The other part would be notifying the browser of the progress. The HTTP protocol does not let you send multiple responses, so using res.send(progress)
is not possible.
但是,您可以继续发送部分响应,直到完成为止。在不关闭它的情况下写入res就像 res.write(string)
一样简单,但访问响应可能更难:使用AJAX或WebSockets访问部分响应?
However, you can keep sending partial responses until it finishes. Writing something to res without closing it is as simple as res.write("string")
, but accessing the response can be harder: Accessing partial response using AJAX or WebSockets?
您还需要一种方法来从支持服务器包装正文(以及错误),以便它可以作为最终的部分响应。
You also need a way to wrap the body (and also errors) from the backing server so that it can fit as the final partial response.
另一种解决方案是打开另一个WebSocket请求跟踪上传/下载过程。 socket.io是一个很好的节点库,用于此目的。
Another solution would be opening another WebSocket request to track the uploading/downloading process. socket.io is a good library for node for this purpose.
这篇关于Node.js进度指示器反馈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!