I've been grappling with the concept of return $http.post('/some link')
and can't seem to fully grasp it.
Imagine I have a node/express backend and am utilizing Angular for my frontend. Within my api, there is a function like this:
var api = express.Router();
//other code
api.post('/login', function(req,res) {
User.findOne({username:req.body.username})
.select('password').exec(function(err, user) {
if (err) {
res.send(err);
return;
} else {
if (!user) {
res.json({message: 'user does not exist!'});
} else {
var validPassword = user.comparePassword(req.body.password);
if (!validPassword) {
res.json({message: 'invalid password!'});
} else {
var token = createToken(user);
res.json({
success: true,
message: "successfully logged in",
token: token
});
}
}
}
})
});
To fetch data from the backend, I establish an angular factory service like so:
var authService = angular.module('authService', {});
authService.factory('Auth', function($http, $q) {
var authFactory = {};
//authToken: factory which has methods to get and set token
authFactory.login = function(username, password, authToken) {
return $http.post('/login', {
username: username,
password: password
})
.then(function(err, data) {
if (err) {
console.log(err);
} else {
AuthToken.setToken(data.token);
return data;
}
})
}
});
In general, the POST method sends data to the backend but doesn't necessarily return anything. However, since $http.post returns a promise object, that object is what we're actually returning. Specifically, in my case, this object looks like this:
res.json({
success: true,
message: "successfully logged in",
token: token
});
So, am I on the right track with my understanding? Despite poring over the Angular documentation repeatedly, I still feel like something might be eluding me here.