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 Express Basics Deeper into Routing with Express The Request Object

understanding .use

he very briefly discussed .use, but it seems like a very important method in express. im a little confused what it does. would we have to do app.use for each require or only for body-parser? thanks!

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

app.use() is for adding middleware. https://expressjs.com/en/guide/using-middleware.html

An assembly line is a good metaphor for middleware. As the request is moving along to a certain destination, it travels through different middleware processes that can modify the request and do certain logic. Middleware are functions. You can use middleware other people have written by installing and requiring a node module, or you could write them yourself. They can do lots of different things depending on the needs of your app: dealing with sessions and cookies, making sure the user is authenticated, handling errors, making sure the request is over https, redirecting the request to another route, and actually returning a response to the client.