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

标签 react-native axios

我有一个Axios拦截器设置,用于管理响应并减少在任何地方的代码重写。当前,我需要在每个调用中使用Authorization对象添加{ config } header ,如下所示。

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拒绝错误。我认为这是因为token返回时仍然是一个不完整的 promise 。

任何想法如何正确处理此配置?
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();

最佳答案

您需要为Axios实例添加request interceptor

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

关于react-native - Axios拦截器-在解决AsyncStorage之前不使用实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49878926/

相关文章:

javascript - Wix react-native-navigation 改变Tab和推屏

javascript - 为什么 axios.get 为 null,而在浏览器中访问时 URL 工作正常?

javascript - 使用 axios 进行 Firebase OAuth 登录和数据访问

javascript - Axios : which HTTP response status codes result in then() and which in catch()?

javascript - 尝试从客户端的 Medium API 访问公共(public)故事时出错

react-native - 防止在 React Native 快速刷新时重置 Redux 状态(expo cli)

android - 有没有办法在用户登录后更改应用程序名称和应用程序图标?

javascript - MobX:观察到的组件在可观察到的变化后不会重新呈现

javascript - React saga 函数没有被调用

javascript - React .map() 不是函数错误