Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Building a MEAN Application Creating and Editing Data in a MEAN App Creating Data with POST Routes in Express

Nicolas Brier
Nicolas Brier
20,443 Points

Response JSON object is missing "name" and "completed"

Using Postman to post this todo object:

{ "name":"TEST", "completed":false }

I get a body answer but the sent info is missing.

{ "todo": { "__v": 0, "_id": "56e5e4e361a997680a8058a0" }, "message": "Todo created ok" }

I couldn't figure out why. Any clue?

Ken Howard
Ken Howard
Treehouse Guest Teacher

If you aren't already, be sure you are using the body-parser middleware in order to capture the body contents sent from the browser request.

Nicolas Brier
Nicolas Brier
20,443 Points

Thanks Ken,

It looks like it's installed properly, here is the content of my package.json file

{ "name": "mean-todo", "version": "1.0.0", "description": "", "main": "src/app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "angular": "^1.5.0", "body-parser": "1.15.0", "express": "4.13.4", "mongoose": "4.4.7" }, "devDependencies": { "webpack": "1.12.14" } }

I tried to uninstall it, then reinstalled it, but indeed it looks like it doesn't work, same result.

Here are my console command

npm install body-parser --save -E mean-todo@1.0.0 /Users/nicobrier/Projects/mean-todo ├─┬ body-parser@1.15.0 │ ├── bytes@2.2.0 │ ├── http-errors@1.4.0 │ ├── iconv-lite@0.4.13 │ ├── qs@6.1.0 │ └─┬ raw-body@2.1.6 │ └── bytes@2.3.0 └── webpack@1.12.14

npm WARN mean-todo@1.0.0 No description npm WARN mean-todo@1.0.0 No repository field. Nicos-iMac:mean-todo nicobrier$ nodemon

Thank you for your help

Can you post the code in your api/index.js file?

15 Answers

Peter Krevenets
Peter Krevenets
19,345 Points

Just found out a solution to my problem - I changed "Text" to "JSON(application/json)" for POST in Postman and now everything works.

Chris Divyak
Chris Divyak
1,982 Points

I was having the same issue and thought it was my code after going through all of the videos again trying to troubleshoot. In the POST method in Postman, you need to specify the data as "raw" and change the type from "Text" (the default) to "JSON(application/json)" also check that the output is JSON. That fixed the issue for me running body-parser version 1.15.0.

Tolgay Budayici
Tolgay Budayici
4,362 Points

Hey guys, I had the same issue and solved it as following:

  • In Postman click on "Headers" and insert "Header" = Content-Type and "Value" = application/json Also make sure that you are sending and receiving JSON.

I hope it helps ! Cheers !

That solved it for me. THANKS!

The problem is the Postman extension. You should use the installed Postman app in your browser, not the extension.

Lakshman Kurri
Lakshman Kurri
1,174 Points

Yes i solved it Just try to move the bodyParser middleware above the router middleware!

var express=require('express'); var app=express(); var router = require('./api'); var parser = require('body-parser'); require('./database'); require('./seed.js'); app.use(parser.json()); app.use('/',express.static('public')); app.use('/api',router);

app.listen(3000,function(){ console.log("The server is running on port 3000"); });

Nicolas Brier
Nicolas Brier
20,443 Points

Hi Iain

Thx for your help. Here it is:

'use strict'; 

var express = require('express');
var Todo = require('../models/todo');
var todos = require('../../mock/todos.json');

var router = express.Router();

// app.get('/api/todos', function(req, res) {
//  // res.send('These are the todos');
//  res.json({todos:[]});
// });

router.get('/todos', function(req, res) {
    Todo.find({}, function(err, todos){
        if(err) {
            // return console.log(err);
            return res.status(500).json({message: err.message});
        } 

        res.json({todos: todos}); //2nd todos = the array import above
    });

});

// TODO: Add POST route to create new entries
router.post('/todos', function(req, res) {
    var todo = req.body;
    // res.send(todo);
    Todo.create(todo, function(err, todo) {
        if(err) {
            return res.status(500).json({err: err.message});
        }
        res.json({'todo': todo, message: 'Todo created ok'});
    })
});

// TODO: Add put route to update entries
router.put('/todos/:id', function(req, res) {
    var id = req.params.id;
    var todo = req.body;
    // if(todo) {
//          res.status(500).json({err: "ok there is a todo"});
//  }
    // if(todo._id !== id) {
//          res.status(500).json({err: "ok todo._id !== id"});
//  }
    if(todo && todo._id !== id) {
            return res.status(500).json({err: "Ids don't match"});
    }
    Todo.findByIdAndUpdate(id, todo, {new: true}, function(err, todo) {
        if(todo && todo._id !== id) {
            return res.status(500).json({err: err.message});
        }
        res.send({'todo': todo, message: 'Todo updated'});  
    })
});




// TODO: add delete route to delete entries

module.exports = router;

Try changing your last response to use res.json() instead of res.send(), and you also only need to check for err from within the Todo.findByIdAndUpdate function call:

    Todo.findByIdAndUpdate(id, todo, {new: true}, function(err, todo) {
        if(err) {
            return res.status(500).json({err: err.message});
        }
        res.json({'todo': todo, message: 'Todo updated'});  
    })
Nicolas Brier
Nicolas Brier
20,443 Points

Thank you for your help Iain. I tried without success. It looks like my issue is on the post method, looks like it is posted, but the body is missing :(

Hmmm well it's possibly your Mongoose schema/model isn't configured correctly, so it's only creating a document in MongoDB with the fields that it automatically adds (_id and __v).

Can you post the code from your models/todo.js file? If you put the language/syntax/file extension after the first lot of three backticks for the code block you will get the syntax highlighting:

    ```js
    function myFunc(arg) {
      return arg;
    }
    ```

Would look like this:

function myFunc(arg) {
  return arg;
}

You can also use a file name:

    ```app.js
    function myFunc(arg) {
      return arg;
    }
    ```

That would look like this:

app.js
function myFunc(arg) {
  return arg;
}
Nicolas Brier
Nicolas Brier
20,443 Points

Thanks Iain

I'm posting my /models/todo.js but I compared to the final files I downloaded and they seem identical. I will continue to check each file. Maybe the json parser does not work, but how could I test that? Thanks for the markdown tip :)

'use strict';

var mongoose = require('mongoose');

// todo.name
// todo.completed

var todoSchema = new mongoose.Schema({
    name: String,
    completed: Boolean
});

var model = mongoose.model('Todo', todoSchema);

module.exports = model;

So you have the following in src/app.js?

var parser = require('body-parser');

and...

var app = express();

app.use('/', express.static('public'));
app.use(parser.json());

You could always set up a new route in src/app.js, just to test the body-parser (make sure it's underneath the app.use statements):

app.post('/post', function(req, res) {
  if (!req.body) {
    return res.sendStatus(400)
  }
  res.json(req.body);
});
Peter Krevenets
Peter Krevenets
19,345 Points

Did you manage to solve this? I have the same problem - no 'name' and 'completed' in response JSON object

Nicolas Brier
Nicolas Brier
20,443 Points

No Peter I'm still stuck here. I'm currently trying to learn more about how mean works... will post here if I found a solution.

Nicolas Brier
Nicolas Brier
20,443 Points

Hi Shon. No I started over and carefully followed all instructions, checked my code against the teacher files, but I was not able to make it work. I just moved on.

I have solved it and edited my answer.

Nicolas Brier
Nicolas Brier
20,443 Points

Great thx I will give it a try.

I had the same problem, however, I realized that I had forgotten to add some codes in src/app.js Adding the code bellow fixed the problem. (video around 3:54)

 var parser = require('body-parser');
.
.
.
app.use('/', express.static('public'));
app.use(parser.json());

Has anyone else solved this issue yet? I also cannot get the todo body to show up.

Emer Kelly
Emer Kelly
217 Points

I changed my code in src/app.js to look like this

app.use('/',express.static('public')); app.use(parser.json()); app.use('/api', router);

instead of

app.use('/',express.static('public')); app.use('/api', router); app.use(parser.json());