简体   繁体   中英

Error handling with axios requests in reactjs

I have an SPA app built in React with many axios calls to an API. I can set up a redirect to the login page within axios when the error status returns 401, but with the large number of calls spread across a lot of components, is there a better way to handle this without repeating the:

if (error.status === 401) {
    //redirect to login page
}

in every single request

Avoid writing the api calls in all the components, create a separate file api.js or some abc.js , and write a generic method of making calls, and call that method from different component with proper parameters. In that case you need to handle all those kind of cases in every file, just put the logic only at one place inside api.js file.

api.js:

export function _callAPI(url, method, data, target){
     /*
         url: separate url for different component
         method: Get or Post or Put etc
         data: if required to pass
         target: callback method
     */
}

Then import this in different component:

import * as Api from 'path to api.js file';

call that by:

Api._callAPI(url, method, data, (data) => {
    console.log(data);
})

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