Async / Await在React的Axios拦截器内部无法正常工作

时间:2020-09-12 13:41:52

标签: reactjs async-await axios

我正在尝试使用async / await来避免在auth令牌过期时多次调用。令牌过期后,其他API调用应一直保留,直到我设置了cookie,但此过程无法按预期工作。有人可以帮我吗?我也尝试过使用Promise,但仍然遇到相同的问题。

下面是我的代码

componentDidMount() {
        const { cookies } = this.props;

        axiosInstance.interceptors.request.use(async request => {
            this.setState({
                error: null
            })
            if (cookies.get('Authorization')) {
                request.headers['Authorization'] = `Bearer ${cookies.get('Authorization')}`;
                request.headers['x-api-key'] = cookies.get('x-api-key');
                return request;
            } else if (window.sessionInterval !== null) {
                const loginRes = await axios.post(`${config.BASE_URL}/login`, {
                    encryptedUserName: this.props.login.userName,
                    encryptedPassword: this.props.login.password
                })
                const { token, sessionInfo, id } = loginRes.data.data;
                const maxAge = convertToSeconds(sessionInfo.JWT_Expiry.toLowerCase());
                cookies.set('Authorization', token, { expires: new Date(), maxAge });
                request.headers['Authorization'] = `Bearer ${token}`;
                request.headers['x-api-key'] = id;
                return request;
            }
        })
        axiosInstance.interceptors.response.use(res => res, error => {
            this.setState({
                error: error
            })
            return Promise.reject(error);
        })
    };

0 个答案:

没有答案
相关问题