Andreas
Andreas

Reputation: 1479

Using post from Angular.js does not work

Ive built a rest-API to add todos in a mongodb. I can successfully save instances by using the following setup in postman:

http://localhost:3000/api/addtodo x-www-form-urlencoded with values text="Test", completed: "false".

Now when I try to replicate this with Angular, it doesnt work, the todo is saved but without the text and completed attributes, I cant seem to access the text or completed values from body. What am I doing wrong? Code below:

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

});

Upvotes: 0

Views: 79

Answers (1)

Ben Fortune
Ben Fortune

Reputation: 32127

$http.post sends it's data using application/json and not application/x-www-form-urlencoded. Source.

If you're using body-parser, make sure you've included the JSON middleware.

app.use(bodyParser.json());

Either that or change your default headers for angular.

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

Upvotes: 2

Related Questions