在React Native中创建axios拦截器时遇到一些问题

时间:2019-12-26 11:32:56

标签: react-native axios

我正在用本地本机创建应用程序,并使用laravel作为后端。为了全局管理错误,我试图创建一个可以处理错误的axios请求拦截器(以前从未创建过),但是,我遇到了错误_api.default.get is not a function

// My Axios Interceptor File

import axios from 'axios';
import {Config} from './common';
import {AsyncStorage} from '@react-native-community/async-storage';

const TIMEOUT = 1 * 60 * 1000;

axios.defaults.timeout = TIMEOUT;
axios.defaults.baseURL = Config.apiUrl;

const axiosInterceptors = async () => {
  const token = await AsyncStorage.getItem('token');

  const onRequest = config => {
    if (token) {
      config.headers.common.Authorization = `Bearer ${token}`;
    }
    return config;
  };

  const onSuccess = response => {
    return response.data;
  };

  const onError = error => {
    return Promise.reject(error);
  };

  axios.interceptors.request.use(onRequest);
  axios.interceptors.response.use(onSuccess, onError);
};

export default axiosInterceptors;

和我的减速器

import axiosInterceptors from "../api"

export const fetchData = () => {
 return dispatch => {
   axiosInterceptors.get(apiUrl).then(something).catch(something)
 } 
}

1 个答案:

答案 0 :(得分:0)

这对我有用

const axiosInterceptors = axios.create({
  baseURL: "your base url",
  timeout: 500,
  headers: {
    Accept: "application/json",
    Authorization: "Bearer "
  }
});

API.interceptors.request.use(
  async function(config) {
    axios.defaults.timeout = 500;
    const token = await AsyncStorage.getItem('token');
    config.headers.Authorization = "Bearer ".concat(token);
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

export default axiosInterceptors;