使用Angular.js的帖子是行不通的
Using post from Angular.js does not work
我构建了一个rest-API来在mongodb中添加todo。我可以通过在poster中使用以下设置成功保存实例:
http://localhost:3000/api/addtodox-www-form-urlencoded with values text="Test",completed:"false"。
现在,当我尝试用Angular复制这一点时,它不起作用,todo被保存,但没有文本和已完成的属性,我似乎无法访问正文中的文本或已完成的值。我做错了什么?以下代码:
Angular HTML:
<div id="todo-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<!-- BIND THIS VALUE TO formData.text IN ANGULAR -->
<input type="text" class="form-control input-lg text-center" placeholder="I want to buy a puppy that will love me forever" ng-model="formData.text">
</div>
<!-- createToDo() WILL CREATE NEW TODOS -->
<button type="submit" class="btn btn-primary btn-lg" ng-click="createTodo()">Add</button>
</form>
</div>
</div>
Angular js:
$scope.createTodo = function() {
$http.post('/api//addtodo', $scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form so our user is ready to enter another
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
REST-API:公司
router.post('/addtodo', function(req,res) {
var Todo = require('../models/Todo.js');
var todo = new Todo();
todo.text = req.body.text;
todo.completed = req.body.completed;
todo.save(function (err) {
if(!err) {
return console.log("created");
} else {
return console.log(err);
}
});
return res.send(todo);
});
$http.post
使用application/json
而不是application/x-www-form-urlencoded
发送数据。来源
如果您使用的是body解析器,请确保包含了JSON中间件。
app.use(bodyParser.json());
要么这样,要么将默认标题更改为angular。
module.run(function($http) {
$http.defaults.headers.post = 'application/x-www-form-urlencoded';
});
相关文章:
- 可以't让我的if语句处理js中的html表单输入
- 使用agility.js进行页面布局和合成
- 使用Clipboard.js复制span文本
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 强制模板刷新ember.js
- 如何编写HTML输入的JS内联
- Angular JS IE9 Hashbang url rewriting
- 使用JS将数组转换为json对象
- Node.js v6.2.0类扩展不是函数错误
- 当js函数's已执行
- 要求未定义JS回调参数
- 在自定义mean.io包中使用angular-chart.js作为依赖项
- 无法在数据endVal中设置值=“”;{{ucount}}”;使用Angular JS的CountUp
- 如何从Java/scala调用js美化程序
- 如何更改<svg>标记为<img>用js标记
- 如何使用 node.js 比较两个 json 数组
- 使用Angular.js的帖子是行不通的
- 棱角分明.js ng-show就是行不通
- Angular JS一步一步的验证是行不通的
- 使用JS在HTML中动态列出JSON项是行不通的