简体   繁体   中英

Axios: which HTTP response status codes result in then() and which in catch()?

Assume we have the following JavaScript code:

axios.get('/some-url')
  .then((response) => {...})
  .catch((error) => {...});

By default, which HTTP status codes of the response result in .then() being invoked, and which in .catch() ?

This is determined by the setting validateStatus .

By default, this is set as follows in lib/defaults.js :

validateStatus: function validateStatus(status) {
    return status >= 200 && status < 300;
}

So, any status codes in the 200's range will result in .then() being called, whereas any other status codes, in .catch() being called.

It can be changed as follows:

let myAxiosInstance = axios.create({
    validateStatus: function (status) {
        return status >= 200 && status < 500;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM