想寻求您的帮助来解决我的代码问题,我是只有一个月经验的Web开发新手。 我的问题是,当我的注册页面使用本地护照策略成功通过身份验证后,它不会重定向到我的其他页面。我已经在这里搜索了很多以前的问题,但是找不到适合我问题的答案。 我使用ajax将数据发布并验证到数据库(mongo)。请参考下面的代码。
路线:
router.post('/register',[
check('firstname','First name name must have at least 2 characters')
.isLength({ min: 2 }),
check('lastname','Last name must have at least 2 characters')
.isLength({ min: 2 }),
check('username','Username name must have at least 2 characters')
.isLength({ min: 2 }),
check('email')
.isEmail().withMessage('Please enter a valid email address')
.trim()
.normalizeEmail()
.custom(value => {
return findUserByEmail(value).then(User => {
//if user email already exists throw an error
})
}),
check('password')
.isLength({ min: 8 }).withMessage('Password must be at least 8 chars long')
.matches(/\d/).withMessage('Password must contain one number')
.custom((value,{req, loc, path}) => {
if (value !== req.body.confirmpassword) {
// throw error if passwords do not match
throw new Error("Passwords don't match");
} else {
return value;
}
}),
check('terms','Please accept our terms and conditions').equals('yes'),
], function(req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.json({status : "error", message : errors.array()});
} else {
var document = {
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email
};
var user = new User(document);
user.save(function(error){
console.log(user);
if(error){
throw error;
}
// res.json({message : "Data saved successfully.", status : "success"});
});
}
next()
}, function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { account : account });
}
// Redirect is not Working Here
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});
});
AJAX帖子:
$(function(){
$("#msgDiv").hide();
$("#btnSignup").on('click', function(event){
event.preventDefault();
var firstname = $("#RegisterFormFirstName").val();
var lastname = $("#RegisterFormLastName").val();
var username = $("#RegisterFormUsername").val();
var email = $("#RegisterFormEmail").val();
var password = $("#RegisterFormPassword").val();
var confirmpassword = $("#RegisterFormConfirmPassword").val();
var terms = $('input[name="terms"]:checked').val();
$.ajax({
url: "/users/register",
method: "POST",
data: { firstname: firstname, lastname: lastname, username: username, email: email, password: password, confirmpassword: confirmpassword, terms: terms }
}).done(function( data ) {
if ( data ) {
if(data.status == 'error'){
var errors = '<ul>';
$.each( data.message, function( key, value ) {
errors = errors +'<li>'+value.msg+'</li>';
});
errors = errors+ '</ul>';
$("#msgDiv").removeClass('alert-success').addClass('alert-danger');
$("#msgDiv").html(errors).show();
}else{
//$("#msgDiv").removeClass('alert-danger').addClass('alert-success').html(data.message).show();
}
}
});
});
});
顺便说一句,我正在使用Node-Express。在此先感谢您的帮助。