Passport.JS 卡在重定向
Posted
技术标签:
【中文标题】Passport.JS 卡在重定向【英文标题】:Passport.JS stuck at redirecting 【发布时间】:2018-06-02 12:52:23 【问题描述】:我的 Express 应用程序中的 Passport.JS 出现问题,更具体地说是注册/登录的成功重定向。用户名/密码没有问题地存储在数据库中,但两种情况下的重定向都不起作用。
我正在使用:Express、Body-Parser、Mongoose、Passport、Passport-local 和 Passport-local-mongoose。
护照配置
app.use(require("express-session")(
secret: "This is a test app",
resave: false,
saveUninitialized: false
));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser);
passport.deserializeUser(User.deserializeUser);
报名路线
app.post("/register", function(req, res)
var newUser = new User(username: req.body.username);
User.register(newUser, req.body.password, function (err, user)
if (err)
console.log(err);
return res.render("register");
passport.authenticate("local"),(req, res, function()
res.redirect("/campgrounds");
);
);
);
登录路径
app.post("/login",
passport.authenticate("local",
successRedirect: "/campgrounds",
failureRedirect: "/login"
));
【问题讨论】:
【参考方案1】:将其写入您的护照配置中 并尝试在您的应用程序中将变量名称与您的匹配
passport.use('local-signup', new LocalStrategy(
// by default, local strategy uses username and password, we will override with email
usernameField : 'usernameFORM',
passwordField : 'passwordFORM',
passReqToCallback : true // allows us to pass back the entire request to the callback
,
function(req, usernameCB, passwordCB, done)
// asynchronous
process.nextTick(function()
// Whether we're signing up or connecting an account, we'll need
// to know if the email address is in use.
User.findOne('username' : usernameCB, function(err, existingUser)
// if there are any errors, return the error
if (err)
return done(err);
// check to see if there's already a user with that email
if (existingUser)
return done(null, false);
// If we're logged in, we're connecting a new account.
if(req.user)
console.log(req.user);
var user = req.user;
User.username = usernameCB;
User.password = user.generateHash(passwordCB);
User.save(function(err)
if (err)
throw err;
return done(null, user);
);
// We're not logged in, so we're creating a brand new user.
else
// create the user
var User = new User();
User.username = usernameCB;
User.password = User.generateHash(passwordCB);
User.save(function(err)
if (err)
throw err;
return done(null, user);
);
);
);
));
在你的路线中
app.post('/signup',passport.authenticate('local-signup',
successRedirect:'/campgrounds',
failureRedirect:'/login'
))
【讨论】:
以上是关于Passport.JS 卡在重定向的主要内容,如果未能解决你的问题,请参考以下文章