Matoy Matoy - 11 months ago 58
AngularJS Question

$http request on node js - how to return a value in success $http.post

I am writing angular + node js app , and I have a login method that validates a user and a password using a http post call:

login.js

$scope.userLogin = function (info) {

$http.post('/authenticate_user', {'name':info.name,'password':info.password})
.success(function(data) {

})
.error(function(data) {
console.log('Error:'+ data);
});


}


on the server.js file I am handling the authnetication:

app.post('/authenticate_user', function(req, res){
authenticate_user(req, res);
});


var authenticate_user=function(req, res){

var query= user_details.find({'name': req.body.name});
res.setHeader("Cache-Control", "private, no-cache, no-store, must-revalidate, max-age=0");
query.exec( function(err, docs){
if (docs.length==0) return false;
res.json(docs[0].password==req.body.password);
});
}


I want to have the userLogin fuction in my login.js file to have the value of the app.post() method..

something like

$http.post('/authenticate_user', {'name':info.name,'password':info.password})
.success(function(data) {
// what is data includes here? the response for the http post?
// or what the function I calling to aka authenticate_user, returns - in this case - a boolean value?
})


I want to have the value from my api post to be transfer to the calling method in the login.js file..

any idea on how to do that?

Thanks

Answer Source

Return a promise instead of hiding it

$scope.userLogin = function (info) {
    return $http.post('/authenticate_user', info);
}

usage

userLogin({name: '', password: ''}).then(function(success) {
  console.log(success)
})