在node.js中获取请求对象数组

时间:2017-08-14 11:33:24

标签: angularjs node.js

我使用AngularJs进行客户端应用,并使用Node.js运行后端。 我必须从客户端发送一些数据到后端标题和正文。

AngularJs代码

$scope.checked_pages=
[
  {
   page_name : BMW,
   pg_id : 123
  },
   {
   page_name : Audi,
   pg_id : 12334
   },
   {.....},
   {......}
];

  $http.post(
      'www.abc.com/../.../index?name=ab',{data: $scope.checked_pages})
    .then(function mySuccess(response) {
       console.log("success ", response);
     }, function myError(response) {
      console.log("Error ", response);

    });

Node.js

        exports.index = (req, res) => {
        var client_name = req.query.name;
        var pgid=req.body.pg_id;
        var pgname=req.body.page_name;

        req.checkBody('name', 'Client name cannot be empty').notEmpty();
        req.checkBody('page_name', 'FB page name cannot be empty').notEmpty();
        req.checkBody('pg_id', 'FB page id cannot be empty').notEmpty();

    const errors = req.validationErrors();

      if (errors) {
        response.fail(res, response.message.parameter_missing, errors);
        return;
      }else{
        var msg = {
                msg: 'data received !'
              };
       response.success(res, msg);
      }
};

问题

当我发送下面的身体数据(单个对象)时,我可以在节点侧获取正文数据。但是当我像上面那样发送array object时,节点侧显示错误。

$scope.checked_pages=
  {
   page_name : BMW,
   pg_id : 123
  };

错误消息 enter image description here

1 个答案:

答案 0 :(得分:0)

错误原因:

responseObject: {page_name: "this is a field inside the response"}
responseArray: [{page_name: "this is a field inside the object inside the response"}]

数组没有任何字段。   数组中只有对象,没有字段,因此在响应中查找字段的测试将执行错误。

可能的解决方案:不依赖于'req.checkBody'

exports.index = (req, res) => {
    var client_name = req.query.name;
    var pgid=req.body.pg_id;
    var pgname=req.body.page_name;

    req.body.forEach((dataItem) => {
        /* WRITE YOUR OWN CODE BELOW */
        // is 'name' field empty?
        // is 'page_name' field empty?
        // is 'pg_id' field empty?
    })

  // Do something with the new knowledge and create 'errors' variable

  if (errors) {
    response.fail(res, response.message.parameter_missing, errors);
    return;
  }else{
    var msg = {
            msg: 'data received !'
          };
   response.success(res, msg);
  }
};