Angularjs向服务器发送请求

时间:2016-08-23 17:38:48

标签: angularjs node.js mean-stack

我如何收集客户端发送的信息?在这种情况下,id?

我如何获得身份证?

我确实使用客户端请求:

    return $http.post('/api/kill', {id:4}, {
              headers: {}
            })

当我检查服务器端为req.body console.log(Req.body)时,我得到:

 { '{"id":4}': '' }

req.body.id返回:

undefined

我怎样才能得到4的身份?

EDIT1:

主要代码位于https://github.com/meanjs/mean

服务器端代码:

app.post('/api/kill', function (req, res) {


        console.log(req.body); // { '{"id":4}': '' }
        console.log(req.body.id); // undefined

    });

4 个答案:

答案 0 :(得分:3)

您需要将id属性分配给

这样的对象

item = { id : 4 }

假设您有一个text-box并且用户想要通过在其中插入名称来保存新项目并单击提交。

让我们假设您使用的是MongoDB个项目集合,为了简单起见,这些项目只有id字段。

这是你应该做些什么来让它变得容易。

确保您要导入bodyParser

var bodyParser = require('body-parser');

HTML - 使用自定义ID

保存新项目
<div class="form-group">
  <label for="id">ID</label>
    <input type="text" class="form-control" id="id" ng-model="ItemController.formData.id">
</div>

<button type="submit" ng-click="ItemController.createItem()" >Submit</button>

Angular part - ItemController.js

'use strict';

angular
    .module('myApp')
    .controller('ItemController', ItemController);

function ItemController($http) {

  var vm = this;

  /** Creates a New Marker on submit **/
  vm.createItem = function() {

          // Grabs all of the text box fields
          var itemData = {
              id        : vm.formData.id
          };

          // Saves item data to the db
          $http.post('/api/kill', itemData)
              .success(function(response) {
                if(response.err){
                  console.log('Error: ' + response.err);
                } else {
                  console.log('Saved '+response);
                }
              });
   };
}

路线处理 - routes.js

var ItemFactory   = require('./factories/item.factory.js');

// Opens App Routes
module.exports = function(app) {

    /** Posting a new Item **/
    app.post('/api/kill', function(req, res) {
        ItemFactory.postItem(req).then( function (item) {
          return res.json(item);
        });
    });

};

发布到MongoDB - item.factory.js

var Item  = require('../models/item-model');
exports.postItem = postItem;

function postItem(item) {
    return new Promise( function (resolve, reject) {  
        var newItem = new Item(item.body);
        newItem.save(function(err) {
            if (err){
                return reject({err : 'Error while saving item'});
            }
            // If no errors are found, it responds with a JSON of the new item
            return resolve(item.body);
        });
    });
}

如果您在我传递项目的不同代码段上尝试console.log(),则可以使用id property正确查看对象。

我希望我一直很有帮助。

答案 1 :(得分:2)

you miss the single quote :

var obj = { 'id':4 };
console.log(obj.id); //display 4

in your example :

 return $http.post('/api/kill', {'id':4}, {
      headers: {}
  })

答案 2 :(得分:2)

你得到的回应不是对象形式

 { '{"id":4}': '' }

它是一个键值对,键是一个字符串

'{"id":4}'

为了在你的最后得到正确的价值,你的json回应应该是

{ { 'id':4 } }

然后它会像

一样工作
    console.log(req.body); // { {"id":4} }
    console.log(req.body.id); // 4

答案 3 :(得分:2)

确保在node.js应用程序中启用了JSON正文解析器。

var bodyParser = require('body-parser');
....
app.use(bodyParser.json());