load middle ware node js code example
Example 1: what is middleware in node js
Notice the call above to next(). Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The next() function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.
Example 2: express router middleware
var express = require('express')
var app = express()
var router = express.Router()
router.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
router.use('/user/:id', function (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
console.log('Request Type:', req.method)
next()
})
router.get('/user/:id', function (req, res, next) {
if (req.params.id === '0') next('route')
else next()
}, function (req, res, next) {
res.render('regular')
})
router.get('/user/:id', function (req, res, next) {
console.log(req.params.id)
res.render('special')
})
app.use('/', router)