简体   繁体   English

使用ReactJS中的axios请求进行错误处理

[英]Error handling with axios requests in reactjs

I have an SPA app built in React with many axios calls to an API. 我有一个内置于React中的SPA应用程序,其中包含许多对API的axios调用。 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: 当错误状态返回401时,我可以在axios中设置重定向到登录页面,但是由于大量调用分散在许多组件上,有没有更好的方法来处理此问题而无需重复以下操作:

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. 避免在所有组件中编写api调用,创建单独的文件api.js或某些abc.js ,并编写进行调用的通用方法,并使用适当的参数从其他组件中调用该方法。 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文件中的一个位置api.js

api.js: 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);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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