【发布时间】:2020-12-11 19:47:11
【问题描述】:
当访问令牌失效时,我不知道如何处理来自服务器的 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();
})
}
我有刷新访问令牌端点 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 端点并设置新令牌,但我不知道如何重新发送主请求(添加帖子)。
【问题讨论】:
-
如果您在使用
async/await时没有任何问题,您可以像let resp = await fetch(...); if (resp.status === 401) { await refershTokens(); resp = await fetch(...); }一样实现它。 (您可以通过在不同的函数中编写递归/重试来避免重复)。
标签: javascript node.js reactjs jwt