简体   繁体   中英

Flush and send response object periodically in Node.js

I am new to Node.js and i am trying to refresh the data periodically using the below code:

router.post('/getMessage',function(req,res){
    setInterval(findMessage,5000);
    function findMessage() {
        Message.find(
            {
                $or: [
                    {sender: req.body.sender, receiver: req.body.receiver},
                    {sender: req.body.receiver, receiver: req.body.sender}
                ]
            },
            (err, data) => {
                res.send({success: true, data: data});
            }
        );
    }
    });

But this gives an error: "Cannot set headers after they are sent". I understand that res.send calls res.end() implicitly and therefore this error is occuring. And have tried res.write() also. But i am returning an object and not a String or buffer, hence it also failed to work.

It would be great if someone could give an example of how to achieve this exactly.

response.send() method does two task

1. write content on the response and send.
2. End connection with res.end().

So, when you did response.send(), then it sends your message and closes the connection. For that reason, you getting the error "Cannot set headers after they are sent".

So, the conclusion is that you can't send multiple responses using response.send().

You can achieve this by the socket.io or you can make the request from frontend after an interval.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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