Middleware are attached to the app object, usually before listen is called. Example of a simple logging middleware:
app.use(function (req, res, next) {
console.log(`${req.method}: ${req.url}`)
next()
})
All this will do is log GET: /example
if you where to GET localhost:3000/example
. All requests will still return 404 since you are not responding with any data.
The next middleware in the chain will be run as soon as the previous one calls next()
, so we can go ahead and respond to the requests by adding yet another middleware like this:
app.use(function (req, res, next) {
res.end(`You requested ${req.url}`)
})
Now when you request ´localhost:3000/exampleyou will be greeted with "You requested /example". There is no need to call
next` this time since this middleware is the last in the chain (but nothing bad will happen if you did),
Complete program this far:
const connect = require('connect')
const app = connect()
app.use(function (req, res, next) {
console.log(`${req.method}: ${req.url}`)
next()
})
app.use(function (req, res, next) {
res.end(`You requested ${req.url}`)
next()
})
app.listen(3000)