【问题标题】:axios keeps returnin 401 when renewing tokenaxios更新令牌时一直返回401
【发布时间】:2019-11-25 00:31:57
【问题描述】:

我在更新令牌以重新执行原始请求后遇到问题。 基本上,在获得并正确设置新令牌后,当我尝试执行原始请求时,我不断收到 Request failed with status code 401

我确定我搞砸了承诺,但我不知道问题出在哪里

// axiosWrapper.js

import axios from 'axios';
import authenticationApi from './authentication';

const baseURL = 'http://apiurl/';
const axiosWrapper = axios.create({
  baseURL,
});

axiosWrapper.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      return authenticationApi.auth()
        .then(res => {
          if (res.status === 200) {
            setToken(res.data.token);
            return axios.request(error.config);
          }
        })
        .catch(err => {
          console.log(err); // Request failed with status code 401
        });
    }

    return Promise.reject(error);
  },
);

axiosWrapper.interceptors.request.use(async config => {
  if (config.url === '/auth') {
    return config;
  }

  var token = await getToken();
  config.headers.Authorization = token ? 'Bearer ${token}' : '';

  return config;
});

export default axiosWrapper;

// authentication.js
import axiosWrapper from './axiosWrapper';

export default {
  auth: () => axiosWrapper.post('auth', {apiKey: 'apiKey'}),
};

【问题讨论】:

    标签: javascript react-native axios


    【解决方案1】:

    经过仔细调试和重构,我意识到问题出在我返回的承诺上,而不是返回新请求的结果。 事实证明,使用 async/await 关键字使其更加清晰。 下面是重构后的样子:

    const baseURL = 'http://server/';
    const axiosWrapper = axios.create({
      baseURL,
    });
    
    axiosWrapper.interceptors.response.use(
      response => response,
      async error => {
        if (error.response.status === 401) {
          if (error.config._retry) {
            return Promise.reject(error);
          }
    
          error.config._retry = true;
    
          const authResult = await authenticationApi.auth()
          if (authResult.status === 200) {
            await setToken(authResult.data.token); // Set token to storage
            error.config.headers.Authorization = `Bearer ${authResult.data.token}`;
    
            const requestResult = await axios.request(error.config);
            return requestResult; // Return the result of the request, not the promise
          }
        }
    
        return Promise.reject(error);
      },
    );
    
    axiosWrapper.interceptors.request.use(async config => {
      if (config.url === 'auth') {
        return config;
      }
    
      const token = await getToken(); // Get token from storage
      config.headers.Authorization = token ? `Bearer ${token}` : '';
    
      return config;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-02
      • 2019-11-20
      • 1970-01-01
      • 2018-06-03
      • 2019-09-03
      • 2017-03-14
      • 2020-11-21
      • 1970-01-01
      相关资源
      最近更新 更多