leonheess
leonheess

Reputation: 21520

Why do I get "Fetch failed loading" when it actually worked?

I use the following code to POST the users position to my own backend-service via the Fetch API:

window.onload = () => {
    let getPosition = (options) => {
        return new Promise((resolve, reject) => {
            navigator.geolocation.getCurrentPosition(resolve, reject, options);
        });
    };

    getPosition().then(pos => {
        const data = new FormData();
        data.append('latitude', String(pos.coords.latitude));
        data.append('longitude', String(pos.coords.longitude));

        fetch('/', {             // <--- error is thrown in this line
            method: 'POST',
            body: data
        }).then(response => {
            if (!response.ok) {
                throw Error('Data sent - Network response NOT OK');
            } else {
                console.log('Data sent - Network response OK')
            }
        });
    });
};

This works flawlessly and the backend-service sends back a positive empty response. Data sent - Network response OK is logged in the browser's console and everything is fine except that immediately after, this is logged:

enter image description here

How come I get a Fetch failed loading: POST even though the POST succeeded, the response is OK and the status code in the Chrome network tab is 200 OK? Is there something wrong with my code?

Upvotes: 27

Views: 18851

Answers (2)

TheHippo
TheHippo

Reputation: 63189

This happens because you don't read the empty response body. I noticed this, because Django triggers a broken pipe error on the server side. To fix this, just read the empty body out.

async function fetchSomething() {
    const response = await fetch(url, {
        method: 'POST'
    })
    await response.text()
    return response.ok
}

Upvotes: 14

rewolf
rewolf

Reputation: 5891

I had the same behaviour that you were seeing. My server responded to the POST request with a 204 (Empty Response) and an empty (Content-Length=0) response. I tried changing that to just respond with a "ok" message instead (edit: actually just returning the created object now) and the fetch error log disappeared.

It seems to me that fetch (at least in Chrome) erroneously logs "Fetch Failed" when the response body is empty, even if the request was successful.

Upvotes: 36

Related Questions