AngularJS将请求发布到服务器
我如何收集从客户端发送的信息?在这种情况下,ID?
How would i gather that info im sending from the client? in this case, the id?
如何获取ID?
我确实使用了客户端请求:
I do use client sided request:
return $http.post('/api/kill', {id:4}, {
headers: {}
})
当我在服务器端检查req.body console.log(Req.body)
时,我得到了:
and when i check server sided for req.body console.log(Req.body)
i do get:
{ '{"id":4}': '' }
req.body.id返回:
req.body.id returns:
undefined
如何获取ID为4?
主要代码位于 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
属性分配给类似
You need to assign that id
property to an object like
item = { id : 4 }
假设您有一个text-box
,用户希望通过在其中插入名称并单击提交来保存新项目.
Lets suppose you have a text-box
and the user wants to save a new item by inserting its name in it and click on submit.
让我们还假设您正在使用MongoDB
项集合,为简单起见,这些项仅具有id
字段.
Lets also suppose you are using a MongoDB
collection of items, which have only id
field for simplicity.
这是使它变得容易的方法.
Here's what you should do to get it going easy.
确保要导入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>
角度部分-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);
}
});
};
}
路由处理-route.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
正确看到一个对象.
If you try console.log()
on the different pieces of code where I passed the item, you can properly see an object with id property
.
希望我能对您有所帮助.
I hope I've been helpful.