【问题标题】:Facing some issues while creating axios interceptor in react native在 react native 中创建 axios 拦截器时遇到一些问题
【发布时间】:2019-12-26 20:05:35
【问题描述】:

我正在创建一个反应原生的应用程序并使用 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)
 } 
}

【问题讨论】:

  • 您的 axiosInterceptors 函数没有返回任何内容

标签: react-native axios


【解决方案1】:

这对我有用

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 2021-07-04
    • 2022-10-17
    • 2016-06-02
    • 2020-03-20
    • 2020-09-02
    相关资源
    最近更新 更多