问题是即使登录后我也无法访问受保护的路由,因为中间件检查没有用户会话来访问该受保护的路由。
这是会话中间件
app.use(session({
secret: "secret",
store: store,
saveUninitialized: false,
resave: false,
cookie: {
// secure: true,
maxAge: 1000 * 60 * 10,
sameSite: "none"
}
}))
如果没有登录,客户端应该收到失败消息,否则它会继续到chatRouter。
这是我保护用户必须登录的路线
const user = (req, res, next) => {
if(req.session.user){
console.log(`Dari middleware: ${req.session}`)
next()
} else {
// res.redirect("/login")
// console.log("Sesi chat: " + req.session);
res.json({
session: req.session,
message: "fail"
})
}
}
app.use("/chat", user, (chatRouter));
当我成功登录后向“/chat”发送请求时,我总是收到“失败”消息。
axios.post(`${api}/user/login`, inputJson, {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
if (response.status !== 200) {
throw new Error('Error, status ' + response.status);
}
window.location.href = "/chat";
})
.catch(error => {
console.log(error);
});
我收到的回复
message: "Login succesfully",
session: {
cookie: {…},
user: {…}
},
[[Prototype]]: Object
但是,当我尝试访问“/chat”路线时,它返回
{session: {…}, message: 'fail'}
message: "fail",
session: {cookie: {…}}, //The user session is missing here
[[Prototype]]: Object
我尝试使用像postman & insomnia这样的http客户端软件,会话工作正常,我在登录前无法访问/chat,并且在登录后能够访问它(按预期工作)。
但是当我尝试从我的网站调用 api 时,发生了这样的情况,登录帐户后我仍然无法访问 /chat。
如果您知道解决方案,请帮忙,我已经在这里苦苦挣扎了几个小时🗿。
节点版本:18.17.0 快速会议:1.17.3 快递:4.18.2
您只需要修复两个部分即可。首先按照
User Login上的 Express 文档示例设置
saveUninitialized: true
选项:
app.use(session({
secret: "secret",
store: store,
saveUninitialized: true, //< Set to true
resave: false,
cookie: {
// secure: true,
maxAge: 1000 * 60 * 10,
sameSite: "none"
}
}))
然后在 Axios 中更改
withCredentials: true
选项的位置,如下所示:
axios.post(`${api}/user/login`, inputJson, {
headers: {
'Content-Type': 'application/json',
},
{ withCredentials: true } //< Put here
})
//...