我想通过POST将HTML / AngluarJS页面中的表单数据发送到服务器(NodeJS),提交时我收到400(错误请求)
使用ng-submit的HTML页面:
<div class="container start" ng-controller="adminController">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-body"><h1>Administration</h1>
<!-- form -->
<form class="form-signin" ng-submit="submit()" ng-controller="adminController">
<h2 class="form-signin-heading">Add new Bird</h2>
<select name= "tagType" id= "inputTag" class="form-control" placeholder="Tag Type" ng-modal="bird.tagType">
<option ng-repeat="tag in tags" value="{{option.id}}">{{tag.tagName}}</option>
</select><br/>
<button class="btn btn-primary" ng-click="addTag()">Add Tag</button>
<br/><br/>
<select name = "specie" id= "inputSpecie" class="form-control" placeholder="Specie Category" ng-modal="bird.specie">
<option ng-repeat="specie in species" value="{{option.id}}">{{specie.latinName}}</option>
</select>
<br/>
<button class="btn btn-primary" ng-click="addSpecie()">Add Specie</button>
<br/><br/>
<input type="text" id="inputSex" class="form-control" placeholder="Sex" ng-modal="bird.sex"/>
<br/><br/>
<input type="text" id="inputRFID" class="form-control" placeholder="RFID Value" ng-modal="bird.rfid"/>
<br/><br/>
<textarea id="inputComment" class="form-control" placeholder="Comment" ng-modal="bird.comment"></textarea>
<br/><br/>
<input type="file" ng-model="form.file_avatar" id="file_avatar" />
<br/><br/>
<input class="btn btn-lg btn-primary btn-block" type="submit" id="submit" value="Submit" />
</form>
</div>
</div>
我的控制器脚本
angular.module('test').controller('adminController', function($scope, $http)
{
$http.get('/api/adminPanel').then(function (response) {
// create a blank object to handle form data.
$scope.bird = {};
$scope.species = response.data.species;
$scope.tags = response.data.tags;
$scope.submit = function()
{
console.log(" Get fields values and Insert in the DB !");
// posting Data to server
$http.post('/api/adminPanel/create', {'bird': $scope.bird}).then(function (response) {
// sucess post
});
// failure post
}
});
});
数据库脚本(adminPanel.js)
router.post('/create', function(req, res, next) {
var specie = req.body.specie;
var comment = req.body.comment;
var sex = req.body.sex;
// var birdSpecie = req.body.specie;
// console.log(" the Bird specie is " + birdSpecie);
console.log('the post request: ' + JSON.stringify(req.body));
database.addAnimal(specie,sex,comment).then(function()
{
res.sendStatus(200);}
,next);
});
答案 0 :(得分:0)
您的控制器应该是
angular.module('test').controller('adminController', function($scope, $http){
$scope.bird = {};
$scope.submit = function() {
$http.post('/api/adminPanel/create', $scope.bird).then(function (response) {
console.log(response);// as you need
});
};
});
并且您的服务器端应该是:
router.post('/api/adminPanel/create', function(req, res, next) {
var specie = req.body.specie;
var comment = req.body.comment;
var sex = req.body.sex;
// your rest of code
return res.status(200).send("success") // return 200 and success message
});