5

I would like to know if is there any way of getting the total number of request in a certain path with Expressjs?

3 Answers3

5

Why not to count it by yourself?

let pingCount = 0;
app.get('/ping',(req, res) => {
  pingCount++;
  res.send(`ping world for ${pingCount} times`);
});
dhilt
  • 18,707
  • 8
  • 70
  • 85
  • 1
    I have done that way, was curious if there was any specific method to do it. Thank you! –  Jan 09 '19 at 20:45
4

I created a middleware that will attach with all routes and count visits. Put this before your routes in app.js

let page_visits = {};
let visits = function (req, res, next) {
  let counter = page_visits[req.originalUrl];
  if(counter || counter === 0) {
    page_visits[req.originalUrl] = counter + 1;
  } else {
    page_visits[req.originalUrl] = 1;
  }
  console.log(req.originalUrl, counter);
  next();
};

app.use(visits);
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
1
let count=0;

function countMiddleware(req,res,next){
count++;
if(next)next();
}

app.use(countMiddleware);

function countMiddleware is acting as middleware ,so it will be executed for every request.count variable is incremented for every request that is logged on your server

Tarun Rawat
  • 244
  • 3
  • 9