-1

I am trying to implement a middle ware that accepts any incoming request and logs all the request parameters, so how can I do that using express?

I tried this code but didn't work,

//logger function
app.use(function(req, res, next){
  console.log('%s %s', req.method, req.url);
  next();
});

Thanks.

user1861639
  • 87
  • 1
  • 1
  • 8

2 Answers2

0

As the comments have mentioned: see the document.

I want to warn you another thing:

do not write user's account info(e.g.: email,password) in the log file,it's dangerous!

yangsibai
  • 1,637
  • 12
  • 23
0

You can do something like this:

  /**
   * This is for logging entrance to a specific route.
   */
  static log(req, _res, next) {
    const {
      body,
      query,
      params,
      method,
      originalUrl,
    } = req;
    let info = `Entered ${method} ${originalUrl} `;
    if (Object.keys(body).length) info += `| body: ${JSON.stringify(body)}`;
    if (Object.keys(query).length) info += `| query: ${JSON.stringify(query)}`;
    if (Object.keys(params).length) info += `| params: ${JSON.stringify(params)}`;
    Logger.info(info);
    return next();
  }

and implement it on the route:

testRoute.get('/test', log, TestController.Test);

You can user if for all POST/PUT/GET/DELETE

Or Assayag
  • 5,662
  • 13
  • 57
  • 93