Node express crashes when the response is in a setInterval. I want to test some things in the frontend when the response is delayed a bit. For this I have passed the response as a callback to the setInterval function in my nodeJs Express:
router.post('/survey', userMiddleware.isLoggedIn, (req, res ,next) => {
setInterval(() => {
res.status(200).send({
message: 'Upload success!'
});
}, 3000 );
});
However, I then receive an error:
node:_http_outgoing:576
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/node/node-express-jwt-test/node_modules/express/lib/response.js:794:10)
at ServerResponse.send (/node/node-express-jwt-test/node_modules/express/lib/response.js:174:12)
at ServerResponse.json (/node/node-express-jwt-test/node_modules/express/lib/response.js:278:15)
at ServerResponse.send (/node/node-express-jwt-test/node_modules/express/lib/response.js:162:21)
at Timeout._onTimeout (/node/node-express-jwt-test/routes/router.js:83:22)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
code: 'ERR_HTTP_HEADERS_SENT'
}
Node.js v17.5.0
[nodemon] app crashed - waiting for file changes before starting...
What's going on?
CodePudding user response:
You keep sending the response at an interval of 3000ms _ the delay is done but the it’s repeated
Use the ‘setTimeout(function, 3000)’ to send once
Read more about set timeout here https://www.w3schools.com/jsref/met_win_setTimeout.asp
So your code Should be like this
router.post('/survey', userMiddleware.isLoggedIn, (req, res ,next) => {
setTimeout(() => {
res.status(200).send({
message: 'Upload success!'
});
}, 3000 );
});