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

发送两个请求的相同访问令牌。刷新请求后,它不会更改授权头。只有当我刷新页面时它才会改变。
发布于 2022-08-08 01:34:41
当axios启动一个请求时,它会在此时接受所有的配置()。因此,当您使用新令牌更新默认配置时,它不会修改而不是修改在之前发送的请求的配置。因此,error.config包含旧的令牌。你需要直接修改它。
我们可以修改这个块:
if(response.status===200){
axios.defaults.headers.common['Authorization']='JWT '+response.data.token
return axios(error.config)
}至:
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)
}https://stackoverflow.com/questions/73269076
复制相似问题