【问题标题】:Using post from Angular.js does not work使用来自 Angular.js 的帖子不起作用
【发布时间】:2015-02-09 12:05:46
【问题描述】:

我已经构建了一个 rest-API 来在 mongodb 中添加待办事项。我可以通过在邮递员中使用以下设置成功保存实例:

http://localhost:3000/api/addtodo x-www-form-urlencoded 值 text="Test",完成:"false"。

现在,当我尝试使用 Angular 复制它时,它不起作用,待办事项已保存但没有文本和已完成属性,我似乎无法从正文访问文本或已完成值。我究竟做错了什么?代码如下:

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

});

【问题讨论】:

  • 确保在 todoform 页面中添加了控制器

标签: javascript angularjs node.js mongodb express


【解决方案1】:

$http.post 使用application/json 而不是application/x-www-form-urlencoded 发送它的数据。 Source.

如果您使用的是正文解析器,请确保您已包含 JSON 中间件。

app.use(bodyParser.json());

要么更改默认标题,要么更改 Angular 的默认标题。

module.run(function($http) {
    $http.defaults.headers.post = 'application/x-www-form-urlencoded';
});

【讨论】:

  • 嗯,我有 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false }));在我的 app.js 中,但它不起作用?
猜你喜欢
  • 2016-03-16
  • 1970-01-01
  • 2018-12-21
  • 2018-12-15
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多