【问题标题】:Angular http.post sending empty jsonAngular http.post 发送空 json
【发布时间】:2017-03-08 17:33:36
【问题描述】:

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

这是我的控制器:

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

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

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

如何处理这个问题?

【问题讨论】:

  • 标题内容类型的问题。

标签: javascript angularjs json node.js


【解决方案1】:

尝试替换:

$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,您可以将其添加到您的默认选项中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 2023-03-31
    相关资源
    最近更新 更多