0

How to handle 404 pages when I'm also trying to catch urls with dynamic parameters? I.e., /:id

The code below never reaches the last rule for 404, and Express always tries to open html file even when they don't exist.

const express = require('express');
const app = express();

app.use(express.static(__dirname + '/dev'));

app.get('/', function(req, res) {
  res.sendFile(`${__dirname}/dev/index.html`);
});

app.get('/:id', function(req, res) {
  res.sendFile(`${__dirname}/dev/pages/${req.params.id}.html`);
});

app.get('*', function(req, res) {
  res.status(404).sendFile(`${__dirname}/dev/404.html`);
});

app.listen(3000, function() {
  console.log('Express server started http://localhost:3000');
});
Luke
  • 2,976
  • 6
  • 34
  • 44
  • Maybe you need error handler middleware: https://expressjs.com/en/guide/error-handling.html#writing-error-handlers – Loki Sep 18 '19 at 21:53
  • Possible duplicate of [How to redirect 404 errors to a page in ExpressJS?](https://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs) – Sasuke Uchiha Sep 19 '19 at 06:07
  • Thats does not seem a good design, I would have a route with a dynamic url param after a some path, - app.get('//:id). – Sándor Bakos Sep 19 '19 at 06:54

1 Answers1

1

Your code will never reach the 404 rule. You need to handle the 404 error from within the dynamic route itself. Since you have defined dynamic parameter after the root path, path after that would go into that route and will never reach 404 rule.

Vinay Shrestha
  • 266
  • 2
  • 8