Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving streamed data using Fetch API in Firefox

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?

like image 762
Yashas Avatar asked Oct 22 '25 18:10

Yashas


1 Answers

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');
like image 140
Adrian Vargas Avatar answered Oct 24 '25 07:10

Adrian Vargas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!