当访问令牌过期时,我使用 axios 拦截器来刷新令牌。这是我的代码:

import axios from 'axios'
import jwt_decode from "jwt-decode";
import dayjs from 'dayjs'


const baseURL = 'http://127.0.0.1:8000'


let authTokens = localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null

const axiosInstance = axios.create({
    baseURL,
    headers:{Authorization: `Bearer ${authTokens?.access}`}
});

axiosInstance.interceptors.request.use(async req => {
    if(!authTokens){
        authTokens = localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null
        req.headers.Authorization = `Bearer ${authTokens?.access}`
    }

    const user = jwt_decode(authTokens.access)
    const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 1;

    if(!isExpired) return req

    const response = await axios.post(`${baseURL}/api/token/refresh/`, {
        refresh: authTokens.refresh
      });

    localStorage.setItem('authTokens', JSON.stringify(response.data))
    req.headers.Authorization = `Bearer ${response.data.access}`
    return req
})


export default axiosInstance;

但是我在调​​用多个请求时遇到问题,它进入无限循环。任何人都可以帮我解决它。提前致谢!


只需使用setInterval(() => { your code here })即可:D

你可能会看到一些教程,比如 w3schools 等,他们总是在最后添加 0,比如 :setInterval(() => { do some code }, 0) 但不需要 :D 因为默认是 0 :)


我会将拦截器作为响应拦截器而不是请求拦截器。

axios.interceptors.response.use((response) => {
   return response
}, 
function (error) {
   if (error.response.status === 401) {
     ...fetch token and retry
   }

通过额外的支持信息可以改进您的答案。请进行编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好的答案的更多信息。

你是什么意思?我应该在哪里使用 setInterval 来解决这个问题?这样做的目的是什么?你能向我解释一下吗?我是 axios 拦截器的新手,所以...:((

在pro-coder中:性能是非常非常重要的一点,pro-coder性能会让你的代码更好,但是如果你的cpu太高那么它会非常非常滞后,所以pro-coder不会总是刷新整个axio而不是umm …就像:我想做一个可以更新每一帧位置的东西,然后我们只需调整位置,而不刷新整个 axio / 游戏,否则: