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

Cannot read property 'body' of undefined

I've reviewed the video multiple times and I'm not seeing my error. Can anyone help?

app.js

'use strict';

var express = require("express");
var app = express();
var jsonParser = require("body-parser").json;

var jsonCheck = function(req, res, next){
    if(req.body){
        console.log("The sky is", req.body.color);
    } else {
        console.log("There is no body property on the request");
    }
    next();
};

app.use(jsonCheck());

app.use(jsonParser());

app.use(jsonCheck());

var port = process.env.PORT || 3000;

app.listen(port, function() {
    console.log("Express server is listening on port:  ", port);
});
Error:

if(req.body){
           ^

TypeError: Cannot read property 'body' of undefined

Can you provide a link to the video?

1 Answer

I should also state that this code was only used as an example and was deleted and replaced with other code. It is not critical to completing the video sequences or the exercise, but I am still curious as to why it does not work.

The video can be viewed: here.