Axios拦截器 - 在AsyncStorage解决之前不使用实例?

时间:2018-04-17 13:03:39

标签: react-native axios

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

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中执行此操作,但我收到了拒绝承诺的错误。我认为这是因为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();

1 个答案:

答案 0 :(得分:5)

您需要为Axios实例添加request interceptor

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