我正在使用NodeJS以角形添加新條目。但是,當我單擊創建時,它不會將數據輸入到數據庫。我添加了angular.toJson來將輸入轉換爲一個json以輸入到Mongodb,但它不起作用。我該如何解決這個代碼以將表單入口數據添加到數據庫?NodeJS/Angular - 從表單添加輸入
角添加控制器
.controller('AddNew', function($scope, $http) {
$scope.addnew = "Add New item";
$scope.item = {};
$scope.create = function() {
item = $scope.item;
var input = angular.toJson(item);
$http.post("http://localhost:3000/api/book", input);
}
})
的NodeJS代碼
//Add a new book
app.post("/api/book", function(req, res){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma,
Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "POST");
console.log("Adding new Book: " + req.body.name);
var book = new Book({
name:req.body.name,
isbn: req.body.isbn,
author: req.body.author,
pages: req.body.pages
});
//Saving the model instance to the DB
book.save(function(err, result){
if (err) throw err;
res.json({
message:"Successfully added book",
book:result
});
});
});
只是注意到一個錯字:'messaage' – moffeltje
如果你正在獲取req.body,那麼它應該工作,否則使用節點模塊bodyparser –