angularjs - POST from angular.js doesn't work but directly from form works. Why? -
i'm working on basic authentication project in node.js using passport.js , it's localstrategy method. it's without password validation yet. accounts stored in mongodb instance.
i stuck whole day when in course i'm going through instructor recommended binding form data angular , sending $http.post()
there, so:
$scope.signin = function (username, password) { $http.post('/login', {username: username, password: password}) .then(function (res) { if(res.data.success) { console.log('logged in'); } else { console.log('error logging in'); } }) };
and here's route it:
app.post('/login', function (req, res, next) { var auth = passport.authenticate('local', function (err, user) { if(err) { return next(err); } if(!user) { res.send({success: false, user: user}); } req.login(user, function (err) { if(err) { return next(err); } res.render('index', { success: true, user: user }); }); }); auth(req, res, next); });
except returned { success: false, user: false }. after ton of googling i've decided make post request directly form:
jade:
.navbar-right(ng-controller='navbarloginctrl') form.navbar-form(action='/login' method='post') .form-group input.form-control(name='username' placeholder='username', ng-model='username' required) .form-group input.form-control(name='password' type='password', placeholder='password', ng-model='password' required) button.btn.btn-default(type='submit' value="submit") sign in
as opposed to:
.navbar-right(ng-controller='navbarloginctrl') form.navbar-form .form-group input.form-control(name='username' placeholder='username', ng-model='username' required) .form-group input.form-control(name='password' type='password', placeholder='password', ng-model='password' required) button.btn.btn-default(ng-click='signin(username, password)') sign in
submit approach works i'd keep things clean , angular. how can it?
other passport.js components reference:
var user = mongoose.model('user'); passport.serializeuser(function (user, done) { if (user) { done(null, user._id); } }); passport.deserializeuser(function (id, done) { user.findone({_id: id}).exec(function (err, user) { if(user) { return done(null, user); } else { return done(null, false); } }); }); passport.use(new localstrategy( function (username, password, done) { user.findone({username: username}, function (err, user) { if (user) return done(null, user); else return done(null, false); }); } ));
you should check browser send.
your broswer form send data in form username=&password=, angular post them in json {username:, password:} , content-type header different.
if want same in angular :
var headers={ 'content-type': 'application/x-www-form-urlencoded; charset=utf-8'}; return $http.post(backendpoint+'/login','username='+username+'&password='+password, {headers:headers}).then(function(result){ });
this use against spring authentication.
Comments
Post a Comment