Full series: Building website with Nodejs - A post from my experience
Previous post: Nodejs - Express with ejs/stylus basics
Middleware
Simply, middleware are just functions for handling requests from client. Each request can have be associated with a stack of middleware. That means when you have several of handler functions associated with one request, they will be executed sequentially. Back to the example from my previous post
app.get('/', middleware1);
function middleware1(req, res){
res.render('index', { title: 'Express', check: true });
};
In this example, there is only one middleware (handler) function for the GET
request to /
. Now we will add one more middleware, or maybe more if you want
app.get('/', middleware1, middleware2);
function middleware1(req, res, next){
// do something here
// ...
// activate the next middleware, otherwise, the next middleware will never be
// called and the client will wait until timeout
next();
};
function middleware2(req, res){
res.render('index', { title: 'Express', check: true });
};