我正在尝试在名称字段中保存数据,但尽管POST请求正在运行且没有任何错误,但mongodb集合仅显示 _id 和 _v 更新。
简而言之,我无法在特定领域保存数据。
查看:
<div id="bookslist" class="row" ng-controller="poster as po">
<form ng-submit="po.createTodo()">
<div class="col-sm-7 form-group">
<label for="" class="col-sm-2">Name</label>
<input type="text" name="" value="" placeholder="" ng-model="po.book.name" class="col-sm-6">
</div>
<div class="col-sm-7 text-right">
<button type="submit" class="btn btn-sm btn-success">Submit</button>
</div>
</form>
</div>
控制器:
app.controller('poster', ['$http', function($http) {
var self = this;
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
};
self.createTodo = function() {
console.log('Ouch baby!!');
$http.post('http://localhost:3000/test',{'name': self.book }, config)
.then(function(response) {
console.log(self.book);
console.log('data is '+response); // data is [object Object]
console.log(response + " added"); //[object Object] added
}, function(errResponse) {
console.log('Error: ' + errResponse.statusText);
console.log(errResponse.status);
});
};
}]);
路线:
'use strict';
module.exports = function(app) {
var bookList = require('../controllers/testController');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Content-Type', 'application/x-www-form-urlencoded;charset=utf-8");
next();
});
app.route('/test')
.get(bookList.list_all_books)
.post(bookList.create_a_books);
};
testController.js(我在设置API时创建的):
'use strict';
var mongoose = require('mongoose'),
menu = mongoose.model('test');
exports.list_all_menus = function(req, res) {
menu.find({}, function(err, menu) {
if (err)
res.send(err);
res.json(menu);
console.log(res);
});
};
exports.create_a_menu = function(req, res) {
var new_menu = new menu(req.body);
new_menu.save(function(err, menu) {
if (err)
res.send(err);
res.json(menu);
});
};
exports.read_a_menu = function(req, res) {
menu.findById(req.params.menuId, function(err, menu) {
if (err)
res.send(err);
res.json(menu);
});
};
exports.update_a_menu = function(req, res) {
menu.findOneAndUpdate({_id: req.params.menuId}, req.body, {new: true}, function(err, menu) {
if (err)
res.send(err);
res.json(menu);
});
};
exports.delete_a_menu = function(req, res) {
menu.remove({
_id: req.params.menuId
}, function(err, menu) {
if (err)
res.send(err);
res.json({ message: 'bestseller_books successfully deleted' });
});
};
注意:
没有保存名称,而名称是集合中的第二个字段。
答案 0 :(得分:0)
你试过$http.post('http://localhost:3000/test',{'name': self.book.name }, config)
吗?
在html模板中使用ng-model="po.book.name"
或
只需将其重命名为book_name
$http.post('http://localhost:3000/test',{'name': self.book_name }, config)
ng-model="po.book_name"