首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Axios拦截器问题

Axios拦截器问题
EN

Stack Overflow用户
提问于 2022-08-07 16:13:33
回答 1查看 110关注 0票数 0

我对axios有异议。我得到了新的访问令牌,但是它没有发送带有进一步请求的更新访问令牌,而且我得到了相同的未经身份验证的错误。

代码语言:javascript
复制
import axios from 'axios'

axios.defaults.baseURL='http://127.0.0.1:8000/api/'
axios.defaults.headers.common['Content-Type']='application/json'

let refresh = false

axios.interceptors.response.use(res =>res ,async error =>{
    if (error.response.status === 401 && !refresh ){
        refresh=true
        const response= await axios.post('/user/refresh/',{},{withCredentials:true})
        
        if(response.status===200){
            axios.defaults.headers.common['Authorization']='JWT '+response.data.token
            return axios(error.config)
        }
        

        }
        
    refresh=false
    return error
})

发送两个请求的相同访问令牌。刷新请求后,它不会更改授权头。只有当我刷新页面时它才会改变。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-08 01:34:41

axios启动一个请求时,它会在此时接受所有的配置()。因此,当您使用新令牌更新默认配置时,它不会修改而不是修改之前发送的请求的配置。因此,error.config包含旧的令牌。你需要直接修改它。

我们可以修改这个块:

代码语言:javascript
复制
if(response.status===200){
            axios.defaults.headers.common['Authorization']='JWT '+response.data.token
            return axios(error.config)
        }

至:

代码语言:javascript
复制
if(response.status===200){
    // we update the new token here but it does not affect the config of the previous request. 
    // error.config is not updated.
    axios.defaults.headers.common['Authorization']='JWT '+response.data.token
    
    // now we resend the request that produces the error
    // we need to update the config directly
    error.config.headers['Authorization'] = 'JWT '+response.data.token
    return axios(error.config)
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73269076

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档