0
我需要身體驗證和更好的錯誤處理沒有第一個驗證中間件。代碼工作得很好,但我想刪除第一個中間件並在第二個時間內進行驗證。Passport.js本地登錄與身體驗證和錯誤處理
路線/ auth.js
router.post('/signin', function(req, res, next){
req.checkBody('email', 'Email is required.').notEmpty();
req.checkBody('email', 'Invalid email format.').isEmail();
req.checkBody('password', 'Password is required.').notEmpty();
req.checkBody('password', 'The password length must be between 8 and 100.').isLength({min: 8, max: 100});
var err = req.validationErrors();
if (err) {
res.status(400).send({ success: false, error: err});
return;
}
next();
});
router.post('/signin', passport.authenticate('local', { session: false }), function(req, res){
var user = req.user;
return res.json({success: true, user: user});
});
至於錯誤處理,如果用戶不匹配,錯誤的是:
{
"error": "Invalid email and/or password"
}
,我想這一點:
{
"success":false,
"error": "Invalid email and/or password"
}
我該怎麼辦?
passport.js
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(email, password, done) {
User.findOne({ email: email, password: password },'-password', function (err, user) {
if (err)return done(err);
if(!user){
var err = new Error('Invalid email and/or password');
err.status = 401;
return done(err, false);
}
return done(null, user);
})
}
));
感謝您的答覆。