1

I have a fairly straight forward logging middleware function in an Express JS app:

app.use(function (req, res, next) {
  const line = `${req.method} ${req.originalUrl} ${res.statusCode}`
  console.log(line)
  next()
})

And I have this route:

this.app.use('/404', function (req, res) {
  res.sendStatus(404)
})

Which logs the following:

GET /404 200

With other routes it seems to always return 200.

How can I fix this so that it accurately logs status codes without changing routes?

Edit

My goal here was something quick to tell me if a route was hit and whether or not it succeeded. I don't want to have to edit all my routes to be compatible with it since I'll eventually replace it with an actual logging solution.

jasminedevv
  • 31
  • 1
  • 6

3 Answers3

0

This still doesn't work for all routes but works for more of them:

this.app.use(async function (req, res, next) {
  await next()
  const line = `${req.method} ${req.originalUrl} ${res.statusCode}`
  console.log(line)
})
jasminedevv
  • 31
  • 1
  • 6
  • Note that awaiting `next()` is useless because it always returns undefined and never a promise. The await will simply go on to the next line without waiting. You've managed to get something working by accident but if you ever have asynchronous code (promise or callback) in any of your middlewares or routes your logger will fail yet again. Express really isn't designed to support your use-case. If you really need to run a middleware after all else you need to call `next()` inside all your routes: https://stackoverflow.com/questions/24258782/node-express-4-middleware-after-routes – slebetman May 21 '20 at 22:10
  • Weirdly, it works for more routes with the await there but you're right it doesn't cover all of them. All the routes in the project use async/await. – jasminedevv May 21 '20 at 22:41
  • That's because of the design of `await`. It only waits if given a Promise but silently continues on if you give it anything else. This is so that functions can optionally return a real value instead of a promise if needed so you don't need to wrap return values in a redundant `Promise.resolve()`. It's not that it doesn't work it's just that it's useless – slebetman May 22 '20 at 04:31
0

Depending of : https://expressjs.com/guide/error-handling.html

app.use('/404', function (req, res) {
  console.error(err.stack);
  res.status(404).send('not found!');
});

Also you can use http-errors module:

var createError = require('http-errors');

app.use(function(req, res, next) {
  next(createError(404));
});
user2226755
  • 12,494
  • 5
  • 50
  • 73
0

Don't know your entire code, but this.app is not necessary. Directly use app.use. Debug, while hitting, you request do not come within app.use('/404'), It might be serving path mentioned above it like app.use('/:variable'), so may be variable == 404. Mention this type of static path topmost.

Paridhi Jain
  • 160
  • 5