DEV Community

Code_Regina
Code_Regina

Posted on

|Middleware| Middleware: The Key to Express

-Intro to Express Middleware
-Using Morgan - Logger Middleware
-Defining Our Own Middleware
-Setting Up a 404 Route

Intro to Express Middleware

Middleware are functions that run at some point during the request and response lifecycle. The functions run between the time a request enters express and by the time the response leaves and the code stops executing. Each middleware function has access to the request object into the response object.
Middleware can end the HTTP request by sending back a response with methods like res.send() or middleware can be chained together one after another

The main job of the middleware is to parse the incoming body of the request and add it to the request object.

Using Morgan - Logger Middleware

https://github.com/expressjs/morgan

Morgan - is a simple logger that helps log HTTP requests information to our terminal. Very useful when debugging things.

Defining Our Own Middleware

Alt Text


app.use(morgan('common'))
app.use((req, res, next) => {
 console.log('This is the first middleware!')
 next(); 
})


app.use(morgan('common'))
app.use((req, res, next) => {
 console.log('This is the second middleware!')
 next(); 
})

Enter fullscreen mode Exit fullscreen mode

the next() statement is there to keep the code moving forward, otherwise the code would end after the console.log statement.

Setting Up a 404 Route

Alt Text


app.use((req, res, next) => {
  req.requestTime = Date.now(); 
  console.log(req.method, req.path); 
  next(); 
}) 

app.use((req, res) => {
 res.status.(404).send('Not Found')
})

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jvon1904 profile image
Jesse vB • Edited

Thanks for sharing! I was following along and the 404 response didn't work. Turns out, we need to lose the dot before the parentheses.

res.status(404).send('Not Found')