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 Build a REST API With Express Building API Routes in Express Accepting Data

Why do we tag ".json" to the end when we require body-parser?

const jsonParser = require('body-parser').json

What does the .json do? Usually I just require modules without adding anything after the parentheses.

1 Answer

Othneil Drew
Othneil Drew
22,421 Points

The body-parser middleware package has different parsing options for handling and transforming data. These include JSON, text, url-encoded form data, and raw data. Requiring the package as require('body-parser).json; simply provides a shorter way for calling it later for use instead of using it like this -> bodyParser.json() you can use it like so -> jsonParser();

Example

// requiring the package
const bodyParser = require('body-parser');
const jsonParser = require('body-parser').json;

// using it for json (these do the same exact thing)
app.use(bodyParser.json());
app.use(jsonParser());

It's more of a styling preference than anything. Hope this helps. -- Drew