Angularjs发送请求到服务器

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

我怎样才能得到这个ID?

我确实使用客户端请求:

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

当我检查服务器双方req.body console.log(Req.body)我得到:

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

req.body.id返回:

 undefined 

我怎样才能得到4的ID?

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

您需要将该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部分 – 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的对象。

我希望我有帮助。

你错过了单引号:

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

在你的例子中:

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

你得到的回应不是以对象的forms出现

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

它是一个键值对,键是一个string

 '{"id":4}' 

为了在你的最后得到正确的价值,你的JSON响应应该是这样的

 { { 'id':4 } } 

然后它会像

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

确保您在node.js应用程序中启用了JSON bodyparsing器。

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