gpt4 book ai didi

reactjs - 重新发送使用过期 token 发出的请求会导致开发人员工具处于待定状态

转载 作者:行者123 更新时间:2023-12-05 06:58:24 25 4
gpt4 key购买 nike

我有一个 React 应用程序,我正在尝试实现 JWT。

我正在使用 axios 拦截器,我在其中捕获服务器由于 token 过期而返回的状态 401,将刷新 token 发送到服务器,在客户端接收新的访问 token ,然后重新发送原始 token 请求失败。

我面临的问题是,当我重新发送最初失败的请求时,状态在开发人员工具的“网络”选项卡中显示为永远挂起。最初失败的请求是一个 POST 请求,当我检查数据库时它被更新了。那么为什么它在开发者工具中显示待定状态呢?

这是我的axios拦截器代码

import axios from 'axios'
// import refreshToken from '../src/Store/refreshToken'
import { store } from '../src/index'
import { removeAuth } from '../src/Store/actions/authAction'

const api = axios.create({
baseURL: process.env.REACT_APP_SERVER
})

function createAxiosResponseInterceptor(axiosInstance) {
axiosInstance.interceptors.request.use(function (config) {
const token = localStorage.getItem('token');
if (token){
config.headers.Authorization = token;
}
return config
}
)

axiosInstance.interceptors.response.use(
response => {
return response;
},
error => {
var errorStatus = error.response.status;


if (errorStatus === 401){ // status 401 is used when token is expired
let cookies = document.cookie
let refresh = cookies.split("refresh=")[1].split(';')[0]
if(!sendRefreshToken(refresh, error)) {
store.dispatch(removeAuth({isLoggedIn: false}));
localStorage.setItem('token', '');
document.cookie = "refresh=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
}
return error
}
);
}

function sendRefreshToken(refreshToken, error) {
let result = api.post('/refresh', {
refreshToken: refreshToken
})
.then(response => {
if (response.data.success && response.data.message === "new access token set") {
localStorage.setItem('token', response.data.newToken)
api({ // Here I am resending the failed request.
method: error.response.config.method,
url: error.response.config.url,
data: JSON.parse(error.response.config.data)
}).then(response => {
console.log(response)
return true
})
.catch(error => {
console.log(error)
return false
})
}
})
.catch(error => {
console.log(error)
return false
})
return result
}



createAxiosResponseInterceptor(api);

export default api;

如果您发现代码有任何问题,请告诉我。让我知道这是否是正确的方法。打开以提供更多赏金积分。

最佳答案

考虑这篇文章以供引用。 https://medium.com/swlh/handling-access-and-refresh-tokens-using-axios-interceptors-3970b601a5da

import axios from 'axios'
// import refreshToken from '../src/Store/refreshToken'
import { store } from '../src/index'
import { removeAuth } from '../src/Store/actions/authAction'

const api = axios.create({
baseURL: process.env.REACT_APP_SERVER
})

function createAxiosResponseInterceptor(axiosInstance) {
axiosInstance.interceptors.request.use(function (config) {
const token = localStorage.getItem('token');
if (token){
config.headers.Authorization = token;
}
return config
}
)

axiosInstance.interceptors.response.use(
response => {
return response;
},
error => {
var errorStatus = error.response.status;

const originalRequest = error.config;

if (
error.response.status === 401 &&
!originalRequest._retry
) {

originalRequest._retry = true;
return api
.post('/refresh', {
refreshToken: getRefreshToken()
})

.then((jsonRefreshResponse) => {
if (jsonRefreshResponse.status === 200) {


// 1) put token to LocalStorage
saveRefreshToken(
jsonRefreshResponse.data.refreshToken
);
// 2) Change Authorization header

const newAccessToken = getJwtToken();

setAuthHeader(newAccessToken);


// 3) return originalRequest object with Axios.
// error.response.config.headers[
// "Authorization"
// ] = `Bearer ${newAccessToken}`;
setAuthHeader(newAccessToken)
return axios(error.response.config);
}
})
.catch((err) => {
console.warn(err);
})

}

if (error.config) {
console.log(error.config);
return Promise.reject();
}
}
);
}

export const setAuthHeader = (token) => {
api.defaults.headers.common["Authorization"] = `Bearer ${token}`;
};



createAxiosResponseInterceptor(api);

export default api;

//These methods could be in separate service class
const getJwtToken=()=> {
return localStorage.getItem("token");
}
const getRefreshToken=() =>{
return localStorage.getItem("refreshToken");
}
const saveJwtToken=(token)=> {
localStorage.removeItem("token");
localStorage.setItem("token", token);
}
const saveRefreshToken=(refreshToken)=> {
localStorage.setItem("refreshToken", refreshToken);
}

关于reactjs - 重新发送使用过期 token 发出的请求会导致开发人员工具处于待定状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64624900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com