How can I handle random garbage in URL's in Express without sending "cannot GET /"?

Viewed 57

How should I handle routes in Express when users enter random URL's that include multiple forward slashes?

For URL's that don't match actual directories I can do this but it is really horrible. When i go to mysite.com/randomNoise/anythingHere/blahblah the following will render my 404...

app.get('/:anything1/:anything2/:anything3', (req, res) => {
  res.render("../theme/404")
})

Like I said, it's not very nice and will not work when even more sub directories are added, I end up with the standard cannot GET / etc Example: mysite.com/something/somethingelse/whatever/extraGarbage

Is there a way to stop Express sending "Cannot GET /" messages or a way to handle when that happens?

1 Answers

You'll be wanting a custom express error handler.

Put code like this after all other app.use() express calls. It takes advantage of the fact that calling next() with a parameter is how you tell express to return an error, rather than a result, to a user.

const createError = require('http-errors')
...

app.use(function (req, res, next) {
  next(createError(404, req.path + ' not found.'))
})

app.use(function (err, req, res, next) {
  /* display a message */
  res.locals.message = err.message
  /* suppress the traceback when not in development */
  res.locals.error =
    req.app.get('env') === 'development' ? err : {}

  if (req.accepts('html')) {
    res
      .status(err.status || 500)
      .render('error')
  } else if (req.accepts('json')) {
    res
      .status(err.status)
      .json({
        status: err.status,
        name: err.name,
        message: err.message
      })
  } else {
    res
      .status(err.status)
      .send(`${err.status}: ${err.message}\r\n`)
  }
})

and create yourself an error.pug template, or use whatever template engine you chose.

You can fiddle around with this code to give the exact error presentation you want.

Related