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 ponents, is there a better way to handle this without repeating the:
if (error.status === 401) {
//redirect to login page
}
in every single request
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 ponents, is there a better way to handle this without repeating the:
if (error.status === 401) {
//redirect to login page
}
in every single request
Share Improve this question edited May 13, 2018 at 13:08 Mayank Shukla 105k19 gold badges162 silver badges145 bronze badges asked Jun 5, 2017 at 18:33 mikeg542mikeg542 4333 silver badges18 bronze badges 1- 2 Sounds like a great job for an interceptor! npmjs./package/axios#interceptors Functions you can define that all requests/responses will route through. Remended way of global error handling when using axios. – Chase DeAnda Commented Jun 5, 2017 at 21:33
1 Answer
Reset to default 7Avoid writing the api calls in all the ponents, create a separate file api.js
or some abc.js
, and write a generic method of making calls, and call that method from different ponent 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 ponent
method: Get or Post or Put etc
data: if required to pass
target: callback method
*/
}
Then import this in different ponent:
import * as Api from 'path to api.js file';
call that by:
Api._callAPI(url, method, data, (data) => {
console.log(data);
})
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745390008a4625619.html
评论列表(0条)