user9227001
user9227001

Reputation:

Get the number of Requests in Express

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

Upvotes: 5

Views: 8108

Answers (3)

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

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);

Upvotes: 4

Tarun Rawat
Tarun Rawat

Reputation: 254

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

Upvotes: 1

dhilt
dhilt

Reputation: 20744

Why not to count it by yourself?

let pingCount = 0;
app.get('/ping',(req, res) => {
  pingCount++;
  res.send(`ping world for ${pingCount} times`);
});

Upvotes: 5

Related Questions