【发布时间】:2016-05-16 16:58:36
【问题描述】:
我正在使用 PassportJS 运行 MEAN 堆栈以进行身份验证,并且我的注册模块与我的 Angular 控制器交互时遇到问题。基本上,errorCallback 永远不会被调用,我不确定如何正确使用 Passport done() 实现。
我有一个基本的注册表单,提交后会调用此请求:
$http.post('/api/signup', {
name: $scope.user.name,
email: $scope.user.email,
password: $scope.user.password,
userSince: new Date().now
}).then(
function successCallback(res) {
$rootScope.message = 'Account Created';
console.log('Success'+res);
console.dir(res,{depth:5});
$location.url('/signupConf');
}, function errorCallback(res) {
$rootScope.message = 'Failure, see console';
console.log('Error: '+res);
console.dir(res,{depth:5});
$location.url('/');
});
有特快路线:
app.post('/api/signup', passport.authenticate('local-signup'),function(req, res) {
console.log('User: ' + req.user.email);
});
最后是 Passport(改编自 Scotch.io tut)模块,略删:
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
console.log("Signup Request: "+email);
process.nextTick(function() {
User.findOne({ 'email' : email }, function(err, user) {
if (err) { return done(err); }
// check to see if theres already a user with that email
if (user) {
console.log("User not created, already exsists: "+user);
return done(err, false, {message: 'Username already exsists.'});
} else {
// if there is no user with that email
// create the user
var newUser = new User();
//a bunch of data creation here
newUser.save(function(err) {
if (err) {throw err;}
console.log("Sucessfully created: "+newUser);
return done(null, newUser);
});
}
});
});
}));
一切正常,创建的用户更正,如果存在具有给定电子邮件的用户,则不会覆盖新用户。但是,无论如何,successCallback 都会被调用。当用户名已经存在时,我可以在浏览器控制台中看到 401 错误。当它是一个错误的请求(即未填写所有字段)时,一个 400 错误。
所有服务器端的 console.logs 工作正常,让我认为我的 Angular 前端有问题,或者后端如何响应请求。
(Scotch.io 教程来源:https://scotch.io/tutorials/easy-node-authentication-setup-and-local)
【问题讨论】:
标签: angularjs node.js express passport.js mean-stack