【问题标题】:axios response interceptor not working properlyaxios 响应拦截器无法正常工作
【发布时间】:2021-05-21 04:09:48
【问题描述】:

我尝试使用带有刷新令牌的 axios 拦截器,但是当我的令牌已过期时。我在interceptors.response 中的错误代码没有执行。我能做些什么来解决这个问题,我也得到一个 200 的状态代码,这对我来说没有多大意义。

这也是我的代码

proctedInstance.interceptors.request.use(
    async config => {
        const accesstoken = localStorage.getItem('accesstoken');
        config.headers = {
            'Authorization': `Bearer ${accesstoken}`,
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        
        return config;
    },
    error => {
        Promise.reject(error);
    }
)

proctedInstance.interceptors.response.use((response) => {
    console.log(response);
    return response
}, 
function (error) {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {

        originalRequest._retry = true;
        return axios.post('http://localhost:4000/refresh_token')
            .then(res => {
                if (res.status === 200) {
                    localStorage.setItem('accesstoken', res.data.accesstoken)
                    console.log('my token res.data.accesstoken', res.data.accesstoken);
                    axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('accesstoken');
                    return axios(originalRequest);
                }
            })
    }

    return Promise.reject(error);
})



export const onProtected = async () => {
    const results = await (await proctedInstance.post('/protected')).data

    if(results.data === 'This is protected data.'){
        return true;
    } else 
        return false;
}

感谢任何帮助

【问题讨论】:

  • 听起来您的后端错误地响应了 200 状态而不是 401
  • 我知道知道是否解决了我以前的问题,但现在我无法让我的 cookie 用新令牌刷新
  • 我在您的问题中没有看到任何使用 cookie 的情况。您指的是localStorage 中的值吗?
  • 我的服务器为 refresh_token 端点发送了一个 cookie,但由于某种原因它似乎无法正常工作
  • 感谢您的帮助,我将令牌设置为非常短的时间,例如 5 秒,现在似乎一切正常。生病继续测试它感谢帮助菲尔

标签: reactjs axios


【解决方案1】:

试着让它这样:

proctedInstance.interceptors.response.use(
    function (response) {
        return response;
    },
    function (error) {
        const access_token = localStorage.getItem("accesstoken");
        if (error.response.status === 401 && access_token) {
            //Your logic to refresh token and reattempt request
        } else {
            console.error(error);
        }
        return Promise.reject(error);
    }
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-25
    • 2022-01-25
    • 2020-09-25
    • 2018-09-27
    • 1970-01-01
    • 2019-04-20
    • 2020-11-21
    相关资源
    最近更新 更多