NodeJS / Angular - 从表单添加输入

时间:2015-11-18 09:26:00

标签: javascript angularjs node.js forms mongodb

我正在使用带有Angular表单的NodeJS添加新条目。但是,当我单击“创建”时,它不会将数据输入到数据库。我添加了angular.toJson来将输入转换为json以输入Mongodb,但它不起作用。如何修复此代码以将表单条目数据添加到数据库?

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

1 个答案:

答案 0 :(得分:1)

更新您的请求代码行,如下所示:

$http({
    method: 'POST',
    url: "http://localhost:3000/api/book",
    data: $.param(item),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

并将这些行包含在服务器端:

app.use(bodyParser.urlencoded({'extended': 'true'}));
app.use(bodyParser.json());

你需要jquery才能使用$.param,如果你没有在你的项目中包含jQuery,你可以绑定这样的参数:

'name='+item.name+'&isbn='+item.isbn

请务必在快速申请中定义body-parser