简体   繁体   English

axios响应拦截器无法处理过期的refresh_token(401)

[英]axios response Interceptor unable to handle an expired refresh_token (401)

I have the following interceptor on my axios response in App.js in ComponentDidMount() and it does not work for all axios request. 我在ComponentDidMount()的App.js中的axios响应上有以下拦截器,它不适用于所有axios请求。

    axios.interceptors.response.use(function (response) {

        if (response)
            return response;
    }, function (error) {

        if (error.response && 401 == error.response.status) {
            console.log('401')
            return Promise.reject(error);
        }
        else {
            return Promise.reject(error);
        }
    });

When I call the API and get an 401 error, this code does not work for me. 当我调用API并收到401错误时,此代码对我不起作用。 I use this code in another component and I can not handle the 401 error 我在另一个组件中使用此代码,但无法处理401错误

  axios
  .get("/web-api/home/", { headers: headers })
  .then(response => {
    this.setState({
      homeconfig: response.data
    });
  })
  .catch((response) => {
    console.log(response);
  });

You have put axios interceptor set in ComponentDidMount. 您已经将axios拦截器设置在ComponentDidMount中。 it is possible that a child component is calling a request before this configuration. 在此配置之前,子组件可能正在调用请求。 (especially if you are calling the request in child component's constructor). (尤其是如果您正在子组件的构造函数中调用请求)。 Therefore, you should do this configuration before any component mount. 因此,您应该在安装任何组件之前进行此配置。 Put your configuration in componentWillMount or constructor (I prefer the constructor because componentWillMount is going to be deprecated in newer versions of react-17). 将您的配置放入componentWillMount或构造函数中(我更喜欢构造函数,因为在更高版本的react-17中将不推荐使用componentWillMount)。

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

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