Following the upgrade to Express 4, and the removal of app.router, I\'m struggling to get middleware to execute after routes execute.
e.g. the following code correct
you can use the Middle ware function in different js file and you can use require function. so that it will be called before and after the http request.
index.js:
const logger = require("./logger");
const express = require("express");
var app = express();
app.listen("3000",()=>console.log("listening on 3000..."))
app.use(logger("AppServer"));
//get expression
app.get("/", function(req,res){
console.log("res not received");
res.send("Hello World");
console.log("res received");
})
logger.js
module.exports = (applicationName) =>{
return function log(req,res,next){
console.log(applicationName+" started "+os.hostname);
res.on("finish",()=>{
console.log(applicationName+" completed "+os.hostname);
})
next();
}};
output:
AppServer started hostname-PC
res not received
res received
AppServer completed hostname-PC
Note: in the logger.js instead of using res.on("finish",callback), you can use req.on("end",callback)