Failed to execute 'json' on 'Response': body stream already read when using setInterval

Viewed 5047

I am trying to update the data (out.rule ) that return of the server every 2000ms to do my business ( i do not write the backend) but get the error : failed to execute 'json' on 'Response': body stream already read .

My post request is :

var fetchURL = fetch("myURL", {
    "headers": {
        "accept": "application/json, text/plain, */*",
        "accept-language": "vi-VN,vi;q=0.9,fr-FR;q=0.8,fr;q=0.7,en-US;q=0.6,en;q=0.5",
        "content-type": "application/json;charset=UTF-8",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "cross-site"
    },

    "referrerPolicy": "strict-origin-when-cross-origin",
    "body": "{myBody}",
    "method": "POST",
    "mode": "cors",
    "credentials": "omit"
});



var refreshIntervalId = setInterval(function() {

    fetchURL.then(res => res.json()).
    then((out) => {
        if (out.rule == admin) {  do something  }
    }).
    catch(err => {
        throw err
    });
    console.log('Error')
}, 2000);
1 Answers

You're already making the fetch on line one. In the interval you're only running .then() over again on the same promise hence you get the mentioned error.

You can fix it by making a function that calls fetch and then call it in each iteration.

Note that the interval may make multiple backend requests before the first request returns, let's say if the backend responds slowly for some reason. You may want to make sure that the previous request has completed before making the next one.

var fetchURL = () => fetch("myURL", {
    "headers": {
        "accept": "application/json, text/plain, */*",
        "accept-language": "vi-VN,vi;q=0.9,fr-FR;q=0.8,fr;q=0.7,en-US;q=0.6,en;q=0.5",
        "content-type": "application/json;charset=UTF-8",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "cross-site"
    },

    "referrerPolicy": "strict-origin-when-cross-origin",
    "body": "{myBody}",
    "method": "POST",
    "mode": "cors",
    "credentials": "omit"
});

var refreshIntervalId = setInterval(function() {

    fetchURL().then(res => res.json()).
    then((out) => {
        if (out.rule == admin) {  do something  }
    }).
    catch(err => {
        throw err
    });
    console.log('Error')
}, 2000);

Related