我在Express应用程序中遇到Passport.JS问题,更具体地说是成功重定向注册/登录。用户名/密码存储在DB中没有问题,但两种情况下的重定向都不起作用。
我正在使用:Express,Body-Parser,Mongoose,Passport,Passport-local和Passport-local-mongoose。
Passport配置
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"
}));
答案 0 :(得分:0)
将此内容写入护照配置中 并尝试在您的应用程序中将变量名称与您的名称进行匹配
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'
}))