简体   繁体   English

从拦截器重复请求后,Axios 结果未定义

[英]Axios result is undefined after request is repeated from interceptor

I'm trying to implement an interceptor which refreshes an expired token and retries the latest request.我正在尝试实现一个拦截器,它刷新过期的令牌并重试最新的请求。 It works for the most part but when the original request is retried res is undefined它在大多数情况下都有效,但是当重试原始请求时res未定义

This is my original request这是我最初的要求

this.$http.post('/auth/verify')
            .then((res) => {
                this.$store.commit('login', res.data);
            })
            .catch((e) => {
                console.error(`Error during verify: ${e}`);
            });

and this is the interceptor I use这是我使用的拦截器

axios.interceptors.response.use(null, (err) => {
if (err.response && err.response.status === 401 && err.response.data.message.includes('jwt expired')) {
    const { refreshToken } = JSON.parse(localStorage.getItem('auth'));
    axios.post('/auth/refresh', { refreshToken })
        .then((res) => {
            axios.defaults.headers.common.Authorization = `Bearer ${res.data.token}`;
            err.config.headers.Authorization = `Bearer ${res.data.token}`;
            localStorage.setItem('auth', JSON.stringify({
                refreshToken,
                token: res.data.token,
            }));

            return axios(err.config);
        })
        .catch((e) => {
            console.error(`Error refreshing token: ${e}`);
        });
    } else {
       return Promise.reject(err);
    }
});

Like I said res is undefined after the request is retried after the interceptor however in the chrome devtools network tab the second request to /auth/verify goes through and returns a correct response which means that the 2nd request to verify was successful.就像我说的,在拦截器之后重试请求后res是未定义的,但是在 chrome devtools 网络选项卡中,对/auth/verify的第二个请求通过并返回正确的响应,这意味着第二个验证请求成功。

我通过让拦截器返回一个解决axios(err.config)的承诺来使它工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM