I am sending data in chunks from a Node.js server whenever a request comes. Expressjs is used.
router.post('/api/test', (req, res) => {
console.log("Started api servicing");
let interval = setInterval(() => {
res.write("Message");
}, 500);
setTimeout(() => {
clearInterval(interval);
res.end("Done");
}, 1000*10);
})
This sends "Message" 20 times over a duration of 10 seconds.
This endpoint is called from the client side using Fetch API. The idea is that I should be able to receive each of the "Message" individually on the client side and this is the implementation I've come up with.
fetch('/api/test', { method: 'POST' })
.then(res => res.body.getReader())
.then(reader => processData(reader))
function processData(reader) {
reader.read().then(({value, done}) => {
console.log(String.fromCharCode.apply(null, value));
if (!done) {
processData(reader)
}
})
return null;
}
I expected the handler function to console log each time "Message" is sent from server i.e every 0.5 second. But in firefox, only after 10 seconds, all the data is console logged at once like:
"MessageMessageMessageMessageMessageMessageMessageMessageMessageMessageMessageMessageMessageMessageMessageMessageMessageMessageMessageDone"
It works correctly in Chrome i.e "Message" is console logged every 0.5 seconds.
Why is this happening and how to fix this behaviour in Firefox?
This question is old but I was having the same issue. I solved it by adding the content type header to the response:
res.setHeader('content-type', 'text/plain');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With