当访问 token 消失时,我不知道如何处理来自服务器的401状态请求。
我在服务器端写了accessTokenVerify:
require('dotenv').config();
const jwt = require("jsonwebtoken");
// Access Token Verify
exports.accessTokenVerify = (req, res, next) => {
if (!req.headers.authorization) return res.status(401).send({ msg: "Access Token is missing." })
const BEARER = 'Bearer';
const auth_token = req.headers.authorization.split(' ');
if (auth_token[0] !== BEARER) return res.status(401).send({ msg: "Access Token is not complete." })
jwt.verify(auth_token[1], process.env.ACCESS_TOKEN_SECRET, (err) => {
if (err) return res.status(401).send({ msg: "Access Token is invalid." })
next();
})
}
而且我有刷新访问 token 端点localhost:5000 / api / auth / refresh。但是我没有如何在获得401状态响应时在客户端实现发送刷新请求的请求。
到目前为止,我有:
const onSubmit = (values: Values) => {
fetch("http://localhost:5000/api/posts", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
name: "Nazwa",
text: "jakiś post",
id: "341324132"
}),
})
.then((response) => {
if (response.status == 401) {
refreshTokens();
[and what next...]
}
return response.json();
})
.then((resp) => console.log(resp))
.catch((err) => {
console.log(err);
});
};
当将refreshTokens()发送到/ refresh端点并设置新 token 时,将请求发送给我,但我不知道如何重新发送主请求(添加帖子)。 最佳答案
我实际上只是自己解决了类似情况。因此,为此,我强烈建议您通过Axios管理您的api请求。从那里,您可以使用axios interceptors
解析请求的响应和错误,进行相应处理,然后使用axios.request(error.config)
重试该请求。