Saturday, 16 February 2019

express: How can you execute a middleware function for every request that comes to the server?


It is very simple, just remove the url argument of the use method.

app.use(function (req, res, next) {
  console.log('Request Count : ' + app.count++);
  next();
});

Above middleware function is called for every request.

HelloWorld.js
//Load express module
const express = require('express');

//Put new Express application inside app variable
const app = express();
app.count = 1;

const port = 8080;

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'));

app.use(function (req, res, next) {
  console.log('Request Count : ' + app.count++);
  next();
});

app.use("/greetMe", function (req, res, next) {
  console.log('Received greetMe request');
  next();
});

app.use("/hello", function (req, res, next) {
  console.log('Received hello request', Date.now());
  next();
});

app.get("/greetMe", (req, res) => {
 console.log("Serving actual response");
 res.send("Hello User, Have a great day!!!!")
} );

app.get("/hello", (req, res) => {
 console.log("Hello!!!!!");
 res.send("Hello User, Have a great day!!!!")
} );

// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));



Previous                                                 Next                                                 Home

No comments:

Post a Comment