Current situtation
I'm trying to make an $http post request from Angular in the following function which is defined in my controller:
$scope.sendUserData = function(){
var userData = JSON.stringify({
'firstName': $scope.firstName,
'lastName': $scope.lastName,
'email': $scope.email
});
console.log(userData); //this prints out the JSON I want
var config = {
headers: {
'Content-Type': 'json'
}
};
$http.post('/api/users', userData, config)
.success(function(data){
console.log(data);
})
.error(function(data){
console.log('Error: ' + data)
});
I have an Express API that I want to receive this $http post request with the route handler defined below:
router.route('/users')
.post(function(req, res){
var user = new User();
user.firstName = req.body.firstName;
user.lastName = req.body.lastName;
user.email = req.body.email;
user.save(function(error){ //add into mongodb
if(error){
res.send(error);
}
else{
res.json({message: 'User created'});
}
});
})
I'm running the front end with npm http-server
which allows me to access my index.html at http://127.0.0.1:8080
in Chrome. I have my express app listen to the same port with the following line app.listen(8080, '127.0.0.1');
Problem
When I try to make the http request from my front end at http://127.0.0.1:8080
the Angular function logs the JSON data I want to the console, but the $http request isn't made and I get the following error in the Chrome console:
POST http://127.0.0.1:8080/api/users 405 (Method Not Allowed)
I can make the http post request successfully from Postman and I see the JSON added into my mongodb collection perfectly.
Am I getting this error because the index.html/front end isn't connecting to the Express app? Fundamentally, I don't understand how this works. Should the Express app be listening to the same port that the index.html is running on? How does this situation of connecting the front end with the back end differ from when an app is running on a local server to when an app is running on the internet?
If someone could explain to me how the front end should connect to the back end, or if I'm doing anything else wrong, I would really appreciate it.
Thanks!