본문 바로가기
TIL: Today I Learned

[TIL] 20201218 Middleware: The Key To Express

by 김알리 2020. 12. 19.

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.