首页 > 解决方案 > 反应 Axios 拦截器并创建不起作用

问题描述

我正在尝试将 Axios 与 React 一起使用。由于我的后端服务使用的是 JWT,所以我编写了一个 Axios 请求拦截器,以在每次向服务器发出请求时添加不记名令牌。下面是代码片段。但是我在axiosinstance.post行中遇到了错误。如果使用 axios.post 则拦截器不起作用。你能告诉我什么是错的以及如何解决这个问题吗?

Uncaught TypeError: Cannot read property 'post' of undefined
    at request (APIUtils.js:9)
    at login (APIUtils.js:23)
    at Login.handleSubmit (login.js:36)
    at HTMLUnknownElement.callCallback (react-dom.development.js:362)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:411)
    at invokeGuardedCallback (react-dom.development.js:466)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:480)
    at executeDispatch (react-dom.development.js:612)
    at executeDispatchesInOrder (react-dom.development.js:637)
    at executeDispatchesAndRelease (react-dom.development.js:743)

代码片段 axiosutilis.js

import axios from "axios";

import { API_BASE_URL, ACCESS_TOKEN } from '../constants';

const axiosinstance = axios.create({
    timeout: 10000,
    params: {} // do not remove this, its added to add params later in the config
});

// Add a request interceptor
axiosinstance.interceptors.request.use(
   config => {
       if(localStorage.getItem(ACCESS_TOKEN)) {
            config.headers.append('Authorization', 'Bearer ' + localStorage.getItem(ACCESS_TOKEN))
       }
       config.headers['Content-Type'] = 'application/json';
       return config;
   },
   error => {
       Promise.reject(error)
});


export default axiosinstance;

APIUtils.js

const request = (options) => {

    if(options.method === 'POST'){
       return axiosinstance.post(options.url, JSON.stringify(options.data))
        .then(response => 
            response.json().then(json => {
                if(!response.ok) {
                    return Promise.reject(json);
                }
                return json;
            })
        );
    }
};

export function login(loginRequest) {

    return request({
        url: "/api/auth/signin",
        method: 'POST',
        data: JSON.stringify(loginRequest)
    });
}

标签: reactjsaxios

解决方案


您的解决方案对我来说很好。请找到我的代码沙箱!如果它不起作用,请告诉我!

https://codesandbox.io/s/cocky-https-tylfu


推荐阅读