Fetch resolves even if 404?

Using this code:

fetch('notExists') // <---- notice 
    .then(
        function(response)
        {
           alert(response.status)
        }
    )
    .catch(function(err)
    {
       alert('Fetch Error : ', err);
    });

This promise is being resolved.

mdn

It returns a promise that allows the response to this request, whether it is successful or not.

Isn't it strange that a failed ajax request is allowed, even if it goes to a nonexistent resource?

I mean, what's next? a fetchto a server that is down and still receiving an allowed promise?

I know that I can investigate a property okin an object response, but still -

Question

Why sampling is allowed for an absolutely incorrect request (non-existing resource).

BTW, jquery query rejected

+4
source share
3 answers

A fetch() , - ( , , ..).

, (404, 500 ..), . , , , .

, , , , . , 404 , :

fetch('notExists').then(function(response) {
    if (response.status !== 200) {
        // make the promise be rejected if we didn't get a 200 response
        throw new Error("Not 200 response")
    } else {
         // go the desired response
    }
}).catch(function(err) {
    // some error here
});

myFetch(), ( -200 ).

( /).

-, , .

, , ( ). "", fetch() , , -, , . , , . , , . , -, .

+7

CORS iirc. , HTTP, , 4xx 5xx.

+1

Use this code ...

fetch(`https://fercarvo.imtqy.com/apps/integradora/DB/corpus.json`)
.then(async (data) => {
    if (data.ok) {
        data = await data.json()
        //Here you have your data...
    }
}).catch(e => console.log('Connection error', e))
0
source

Source: https://habr.com/ru/post/1653464/


All Articles