Angular http.post发送空json

时间:2016-10-26 11:12:24

标签: javascript angularjs json node.js

我在后面有AngularJS和NodeJS的应用程序,当我把我的应用程序放在VPS上时,Angular正在发送一个带有json的帖子,但是对象是完全空的,字段是未定义的。 这是我的代码:

这是我的控制者:

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

我的配置为post提供默认选项:

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

我的问题:

    $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";
         }
    }

(我用cors)我的NodeJS接收:

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");
  });
});

如何处理这个问题?

1 个答案:

答案 0 :(得分:0)

尝试更换:

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

使用:

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

您应指定Content-Type。如果您希望所有$ http.post都是json,那么您可以在默认选项中添加它。