简体   繁体   English

在 Express.js 中计算时如何发送多个响应?

[英]How to send multiple responses while computing in Express.js?

I'm trying to send multiple responses to client while computing.我试图在计算时向客户端发送多个响应。 Here is my example:这是我的例子:

app.get("/test", (req, res) => {
    console.log('test');
    
    setTimeout(() => {
        res.write('Yep');
        setTimeout(() => {
            res.write('Yep');
            setTimeout(() => {
                res.write('Yep');
                setTimeout(() => {
                    res.write('Yep');
                    setTimeout(() => {
                        res.write('Yep');
                        setTimeout(() => {
                            res.end();
                        }, 1000);
                    }, 1000);
                }, 1000);
            }, 1000);
        }, 1000);
    }, 1000);
    
    
});

I want to get the response in every seconds.我想在每一秒内得到响应。 But my code works and it send response on end() .但我的代码有效,它在end()上发送响应。 Is there any way to do it?有什么办法吗?

You can't send more than one response to a request, that's not how HTTP works.您不能对请求发送多个响应,这不是 HTTP 的工作方式。 You can send headers more than once (see this answer ), but only one response body.您可以多次发送标头(请参阅此答案),但只能发送一个响应正文。 You could use websockets or build logic into the client to hit an endpoint every X seconds, if you need functionality like that.如果您需要类似的功能,您可以使用 websockets 或在客户端中构建逻辑以每 X 秒访问一个端点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM