Axios中的请求拦截器更改了请求方法

时间:2019-06-10 12:27:11

标签: reactjs request header axios interceptor

当我添加拦截器以向所有请求添加Auth标头时,我在React应用程序中遇到axios请求拦截器的异常行为。结果,当我在浏览器的“网络”选项卡中检查它时,axios将我的请求方法从GET更改为OPTIONS。我也收到错误“无法处理的拒绝(TypeError):无法读取未定义的属性'status'”。这是我的代码:

    import {itsInstance as itsAxios} from "./axios/axios-config";
    //Other imports...

    class App extends Component {

    constructor(props) {
        super();

        itsAxios.interceptors.request.use(request => {
            console.log('REQUEST', request);
            request.headers.Authorization = `Bearer ${props.token}`;
            return request;
        });

        itsAxios.interceptors.response.use(response => {
            console.log('RESPONSE', response);
            return response;
        }, error => {
            console.log('RESPONSE ERROR', error);
            if (error.response.status === HTTP_STATUS_UNAUTHORIZED || error.response.status === HTTP_STATUS_FORBIDDEN) {
                // console.log("FORBIDDEN");
            } else {
                alert(error);
            }
            return Promise.reject(error);
        });

    }

    render() {
        return (
            <BrowserRouter>
                <React.Suspense fallback={loading()}>
                    <Switch>
                        <Route path="/login" name="Login Page" render={props => <Login {...props}/>}/>
                        <Route path="/" name="Home" render={props => (
                            this.props.token !== null ?
                                <DefaultLayout {...props}/> :
                                <Redirect to='/login'/>)}/>
                    </Switch>
                </React.Suspense>
            </BrowserRouter>
        );
    }
    }

    const mapStateToProps = (state) => {
        return {
            token: state.token
        }
    };

    export default connect(mapStateToProps)(App);

当我删除“ request.headers.Authorization = Bearer ${props.token};”时行它正常工作。 我在构造函数中实例化拦截器的原因是我想访问props.token,可能有比此更好的解决方案

0 个答案:

没有答案