如何强制客户端重定向到登录页面与快速post请求?



我有安全的后端路由,在继续检索数据之前运行verifyJWT函数。如果令牌过期或无效,是否有办法在客户端强制重定向到登录页面?

当我使用res.redirect("/login")时,它对客户端没有影响。

这是我的路由代码。


const verifyJWT = (req, res, next) => {
const token = req.headers.cookie.split("=")[1]
if (!token) {
console.log("No token")
} else {
jwt.verify(token, "mySecret", (err, decoded) => {
if (err) {
res.redirect("/login")
} else {
req.userID = decoded.id
next()
}})}}

我测试过的一条重定向路线。


app.post("/getphotos", verifyJWT, (req, res) => {
const userID = req.userID
db.query("SELECT id, photourl, favorite, photoKey FROM photos WHERE userID = (?) AND trash = 0", 
[userID], 
(err, result) => {
err ? console.log(err) : res.status(200).send(result)
})
})

在阅读了express路由之后,我了解到重定向必须在post请求的客户端完成,以下是我如何实现的。

如果出于某种原因需要注销用户(例如,他们的JWT令牌过期),只需在后端重新路由到注销路由res.redirect("/logout")即可。

app.get("/logout", (req, res) => {
res.send({redirect: "/login"})
})

然后,在客户端,您可以检查响应是否为重定向,然后简单地将它们重定向到您想要的任何页面。

async function getData() {
const response = await axios.post("http://localhost:3001/getData", {body}, {withCredentials: true})
if (response.data.redirect) {
history.replace(`${response.data.redirect}`)
}
}

最新更新