【问题标题】:Axios interceptors - Not using instance until AsyncStorage resolved?Axios 拦截器 - 在 AsyncStorage 解决之前不使用实例?
【发布时间】:2018-04-17 13:03:38
【问题描述】:

我有一个 Axios 拦截器设置来管理响应并减少到处重写代码。目前,我需要在每个调用中使用{ config } 对象添加Authorization 标头,如下所示。

apiCall = () => {
    const token = await AsyncStorage.getItem('JWT_BEARER_TOKEN');
    const config = {
      headers: {
        'Authorization': 'Bearer ' + token,
      }
    }
    const attendance = await axiosInstance.post('/team/matchday', data, config);
    // ... do something with attendance
}

我想在下面创建的axiosInstance 中执行此操作,但我收到了一个 promise denied 错误。我想这是因为token 在返回时仍然是一个不完整的承诺。

任何想法如何正确处理此配置?

import { AsyncStorage, Alert } from 'react-native';
import axios from 'axios';


const ReturnAxiosInstance = async (token) => {
  const AxiosInstance = axios.create({
    baseURL: 'http://localhost:4000',
    timeout: 3000,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + await AsyncStorage.getItem('JWT_BEARER_TOKEN'),
    },
  });

  AxiosInstance.interceptors.response.use(
    response => response,
    (error) => {
      if (!error.response) {
        Alert.alert('Network Error!');
        return console.log(error);
        // return dispatch({ type: 'NETWORK_FAILURE' });
      } else if (error.response.status === 500) {
        Alert.alert('Server Error!');
      } else if (error.response.status === 404) {
        Alert.alert('Endpoint doesn\'t exist!');
      }
      // handle the errors due to the status code here
      return error.response;
    },
  );
  return AxiosInstance;
};
export default ReturnAxiosInstance();

【问题讨论】:

    标签: react-native axios


    【解决方案1】:

    您需要为您的 Axios 实例添加 request interceptor。

     // ...
     axiosInstance.interceptors.request.use(
        async (config) => {
          config.headers.authorization = await AsyncStorage.getItem('JWT_BEARER_TOKEN');
          return config;
        },
        error => Promise.reject(error)
      );
      // ...
    

    【讨论】:

    • 非常感谢。你节省了我的时间
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2019-03-15
    • 2018-01-20
    • 2020-03-08
    • 2020-06-01
    • 1970-01-01
    相关资源
    最近更新 更多