0

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

});
1
  • Make sure that you added controller in the todoform page Commented Feb 9, 2015 at 14:35

1 Answer 1

2

$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';
});
Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, I do have app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); In my app.js, but it doesnt work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.