使用Angular.js的帖子是行不通的

Using post from Angular.js does not work

本文关键字:行不通 js 使用 Angular      更新时间:2023-09-26

我构建了一个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';
});