Req.isAuthenticated变为false
问题描述:
当我登录时,我通过了身份验证,但是当我切换到另一个页面时,req.isAuthenticated返回false,我在登录面板上。第二件事是当我登录时,我总是收到一个错误“发送后无法设置标题”。这里是我的代码:Req.isAuthenticated变为false
当然const isLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
return res.end();
} else {
return res.redirect("/login");
}
}
module.exports = (app, passport) => {
app.post("/login", (req, res, next) => {
passport.authenticate("local-login",
(err, user, info) => {
if(!user) {
res.render("index", { message: "Wrong password or login!" })
} else {
req.login(user, (error) => {
if (error) return next(error);
console.log("AUTH: ", req.isAuthenticated()) <--- RETURNS TRUE
return res.render("map", { name: user.name });
});
}
})(req, res, next);
});
app.get("/", (req, res) => {
return res.render("index"); // load the index file
})
app.get("/login", (req, res) => {
return res.render("index"); // load the index file
})
app.get("/map", isLoggedIn, (req, res) => {
return res.render("map");
});
app.get("/vehicles", isLoggedIn, (req, res) => {
return
});
app.get("/settings", isLoggedIn, (req, res) => {
res.render("settings");
});
app.get("/logout", (req, res) => {
req.logout();
res.redirect("/");
});
};
答
登录页面会给你req.isAuthenticated
true
,因为你只是被passport
中间件认证。
护照将返回req.isAuthenticated
true
,直到你没有得到登出,它会设置req.isAuthenticated假,当你打/logout
路线
所以保持你必须使用会话存储 应用程序的状态的用户状态。
找到以下链接:https://www.npmjs.com/package/express-session
你得到“后,他们被送到不能设置头”。因为你要回复两次。一个是req.isAuthenticated()
变为真的,第二个就像你再次呈现一个map
页面。
所以不是return res.end()
你应该使用next()
const isLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
req.session.isAuthenticated = true;
res.locals.isAuthenticated = true;
res.locals.user =req.user;
next(); //If you are authenticated, run the next
} else {
return res.redirect("/login");
}
}
感谢解释,但并没有帮助。登录后一切正常,但当我点击地图时,我的req.session就像重置 – Miqez