4
我正在执行护照验证到我的节点应用程序,我无法理解为什么在访问响应(res)属性之前需要重定向?护照节点验证成功
app.get('/api/loginFailure', function(req, res) {
res.status(401).json({message: 'Login Failed', success: true});
});
app.get('/api/loginSuccess', function(req, res) {
res.status(200).json({message:'Welcome!', success: true});
});
// process the login form
app.post('/api/login', passport.authenticate('local-login', {
successRedirect: '/api/loginSuccess',
failureRedirect: '/api/loginFailure'}));
正如您所看到的,我使用successRedirect访问不同的路由以发回一个json响应。我不希望节点api重定向实际的应用程序,因为它的目的是为了与前端无关。
本地登录策略如下。我怀疑我的困难可能在于我如何从方法中回归;
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({
'local.email': email
},
function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user) {
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
}
// if the user is found but the password is wrong
if (!user.validPassword(password)) {
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
}
// all is well, return successful user
return done(null, user);
});
}));
我打算删除所有flashdata,什么不是,但现在只能够在2条额外的API路线收缩到/ API /登录将是巨大的。
这正是指南为没有?起点?我明白我可以做你上面强调的内容,但我不明白的是如何从定制策略中返回,以便可以应用上述相同的逻辑。 – Dean 2014-10-17 13:43:12
你已经尝试过使用相同的'passport.use()'块吗? – t0mppa 2014-10-17 20:55:31
我试过app.post('/ login',passport.authenticate('local-login'),function(req,res){});但属性res不可用。这就是为什么我认为我在本地战略中的回报陈述是不正确的。 – Dean 2014-10-20 11:50:42