5.6 Express Middleware


Adding functions onto Express.

Example
app.use(express.static(__dirname + '/public'))

app.use registers a middleware that teaches express to statically connect files in public.


Writing Your Own Middleware

app.use((request, response, next)=>{
next();
})

next() call is important. If you do not provide this, your access is going to stop there and wait for this very next.


Example of a middleware

app.use((request, response, next)=>{
var now = new Date().toString();
console.log(`${now}: ${request.method} ${request.url}`);
next();
})

Example of a maintenance middleware

app.use((request, response, next)=>{
response.render("maintenance.hbs");
})

Problem
Typing http://localhost:3000/help.html still works although we want it to be relayed with maintenance page.

To solve it, we need prioritize middlewares.

app.use((request, response, next)=>{
response.render("maintenance.hbs");
})
app.use(express.static(__dirname + '/public'))

Make sure maintenance is beyond express.static.