反应Axios拦截器并创建不起作用

时间:2019-11-03 01:59:23

标签: reactjs 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)
    });
}

1 个答案:

答案 0 :(得分:1)

您的解决方案对我来说很好。请找到我的代码沙箱!万一它不起作用,请通知我!

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