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 trialaviralkulshreshtha
6,561 PointsWhen to use () [i.e. function call] inside app.use?
Compare: app.use(jsonCheck) and app.use(jsonParser())
Why is jsonParser() explicitly called but the function we defines is not? I'm really confused, conceptually, about this, so any help would be of great help, thanks!
1 Answer
Joel Kraft
Treehouse Guest TeacherHi aviralkulshreshtha,
jsonParser
is 3rd-party middleware from the body-parser library. Very often, 3rd-party middleware will take the form of a function that returns a middleware function. That's what's happening here, something along the lines of the following:
function thirdPartyMiddleware () {
// set up middleware function
// ...
return function( req, res, next ) {
// process req and/or res
next();
}
}
Then, when this function is called, the inner function is passed to app.use
:
app.use( thirdPartyMiddleware() );
A function that returns another function is sometimes referred to as a closure. We have a closure workshop that looks at this a little more closely, if you're interested:
The final video of the workshop, we actually peek under the hood a 3rd-party Express middleware library!
Hope this helps!
aviralkulshreshtha
6,561 Pointsaviralkulshreshtha
6,561 PointsYou're the best, thanks!