im using expressJs and want to execute some middleware at the end of each request.
Is it possible to define this on app-level to avoid defining it on each route?
im using expressJs and want to execute some middleware at the end of each request.
Is it possible to define this on app-level to avoid defining it on each route?
Check this example. The code "console.log('Response sent')" will be executed on the end of each request to any route.
var express = require('express');
var app = express();
function myMiddleware (req, res, next) {
res.on('finish', function() {
console.log('Response sent.');
});
next();
}
app.use(myMiddleware);
app.get('/first', function(req, res, next) {
console.log('[/first] New request recieved.');
res.end('Hi!');
});
app.get('/second', function(req, res, next) {
console.log('[/second] New request recieved.');
res.end('Hi!');
});
app.listen(3000, function(req, res) {
console.log('Listening port 3000');
});
You can use app.use([path,] function [, function...])
for this.
Here's an example from Express' docs:
// this middleware will be executed for every request to the app
app.use(function (req, res, next) {
console.log('Time: %d', Date.now());
next();
})
And of course, you can define a function elsewhere and pass it to the use
method.
function middleware(req, res, next) {
console.log('middleware!');
next();
}
// some other codes maybe
app.use(middleware);