我目前正在开发一个使用MERS堆栈的网站。我正在使用快速会话和护照.js进行后端身份验证。当我尝试从后端服务器登录时,API 工作正常。但是,当我尝试从客户端(React)发送POST请求时,它没有经过身份验证。
我尝试从前端和后端控制台.log请求,并且请求是相同的。我注意到的一件事是,当我没有在我的 API 中放置身份验证中间件时,我的前端在重定向到 API 后获取数据;当我放置中间件时,情况正好相反。
//This is my POST code
router.post(
"/userLogin",
passport.authenticate("local", {
successRedirect: "/api/user",
failureRedirect: "/api/user/asktologin"
}),
(req, res) => {}
);
//This is my middleware
const isLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
console.log(req.isAuthenticated);
} else {
console.log(req);
}
};
您的isLoggedIn
中间件未调用堆栈中的next
函数。它应该看起来像这样
const authenticationMiddleware = (req, res, next) => {
if (req.isAuthenticated()) {
console.log(req.isAuthenticated);
next()
} else {
console.log(req);
res.send(400);
}
};
// Then you configure it like so
app.use(authenticationMiddleware);
// Your "router" config goes here
post("/userLogin",
passport.authenticate("local", {
successRedirect: "/api/user",
failureRedirect: "/api/user/asktologin"
}),
(req, res) => {
// Do stuff
}
);
有关如何使用中间件的更多详细信息,请务必查看文档。