Express Middleware
- Functions that run during the request/response lifecycle.
- request → Middleware → response
- Each middleware has access to the request and response objects
- Middleware can end the HTTP request by sending back a response with method like res.send()
- Or middleware can be chained together, one after another by calling next()
- Middleware functions can perform the following tasks:
- Execute any code
- Make changes to the request and the response objects
- End the request-response cycle
- Call the next middleware function in the stack
Morgan
- Express middleware that helps us log HTTP requests information to our terminal
- Useful for debugging
How to move on to the next middleware
app.use((req,res,next) => {
next(); //invokes the following middleware
})
The Pros of customized middlewares
- We can access information from the request
- We can modify or add data to the request object before any of out route handlers are executed.
Setting up a 404 Route
- app.use([path,] callback [, callback...])
- Mounts the specified middleware function or functions at the specified path
- At the end of all the other routes, add app.use to define unfound pages(404). This will run only when we never sent back anything before, meaning there was no matching route for the request.
- Example
app.use((req, res) => {
res.status(404).send('Not Found');
//status(404) : change the status code to 404
})
Protecting Specific Routes
- Use app.get instead of app.use if we want things to run on certain requests.
- app.get accepts multiple callbacks. Callbacks run in order. So if the first callback doesn't have next() function, the following callbacks will not run.
* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.
'TIL: Today I Learned' 카테고리의 다른 글
[TIL] 20201221 Data Relationships With Mongo (0) | 2020.12.21 |
---|---|
[TIL] 20201219 Handling Errors in Express Apps (0) | 2020.12.19 |
[TIL] 20201217 MongoDB / Mongoose (0) | 2020.12.17 |
[TIL] 20201216 Express / Dynamic HTML with Templating / RESTful Routes (0) | 2020.12.16 |
[TIL] 20201215 The Terminal / Our First Brush with Node / Exploring Modules & The NPM (0) | 2020.12.15 |