Hellhiem Hellhiem - 1 month ago 5
Javascript Question

Angular http.post sending empty json

i have application on AngularJS and NodeJS on the back, when I put my app on VPS, Angular is sending a post with json but object is completely empty, fields are undefined.
Here is my code:

This is my controller:

app.controller('fullAppController', ['$scope','$http','$location','$cookies',function($scope,$http,$location,$cookies)


My config to provide default options for post:

app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.post = {};
}]);


My problem:

$scope.registerSubmitData = function(){
if(propertyCheck($scope.registerData,'userName') &&
propertyCheck($scope.registerData,'email') &&
propertyCheck($scope.registerData,'password') &&
propertyCheck($scope.registerData,'passwordCheck') &&
propertyCheck($scope.registerData,'firstName') &&
propertyCheck($scope.registerData,'lastName') &&
propertyCheck($scope.registerData,'street') &&
propertyCheck($scope.registerData,'streetNum') &&
propertyCheck($scope.registerData,'postCode') &&
propertyCheck($scope.registerData,'city') &&
propertyCheck($scope.registerData,'state')){
console.log($scope.registerData); //HERE IS FILLED OBJECT
$http.post('http://localhost:8000/register', $scope.registerData).success(function(data,status){
// HERE ANGULAR POST A EMPTY JSON
$location.path('/login');
$scope.logInSuccesAlert = true;
$scope.logInSuccesAlertText = "Successfully register";
}).catch(function(err){
$scope.registerAlert = true;
$scope.registerAlertText = "Username exist";
});
}else{
$scope.wrongNoState = true;
$scope.registerAlert = true;
$scope.registerAlertText = "Please fill all fields";
$scope.wrongNoStateText = "Please select state";
}
}


(I'm using cors)My NodeJS receiving:

app.use('/register', function(req,res){
console.log(req.body);
//HERE RECEIVED JSON (req.body) IS EMPTY
var registerData = req.body;
registerData.password = SHA256(registerData.password);
insertUser(registerData).then(function(result){
res.send("Successfully register");
}).catch(function(err){
res.status(409).end("User exist");
});
});


How to handle this problem ?

Answer

Try replacing:

$http.post('http://localhost:8000/register', $scope.registerData).success(function(data,status){ 

with:

$http.post('http://localhost:8000/register', $scope.registerData, { headers: { 'Content-Type': 'application/json' } }).success(function(data,status){ 

You should specify the Content-Type. If you want all your $http.post to be json you may be able to add that in your default options.

Comments