我目前正在开发使用MERS堆栈网站。我使用的快递会话和passport.js我的后台认证。当我尝试从我的后端服务器登录,该API工作正常。然而,当我尝试发送从我的客户端(反应)POST请求时,它没有通过认证。
我试图从CONSOLE.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
}
);
有关如何使用中间件的更多详细信息,请务必检查出docs。