Categories
JavaScript Answers

How to get Express.js to send 404 only on missing routes?

Spread the love

Sometimes, we want to get Express.js to send 404 only on missing routes.

In this article, we’ll look at how to get Express.js to send 404 only on missing routes.

How to get Express.js to send 404 only on missing routes?

To get Express.js to send 404 only on missing routes, we can add a catch-all route at the end of the app.

For instance, we write

const express = require("express");
const app = express.createServer();

const users = [{ name: "abc" }];

app.all("/user/:id/:op?", (req, res, next) => {
  req.user = users[req.params.id];
  if (req.user) {
    next();
  } else {
    next(new Error("cannot find user ", req.params.id));
  }
});

app.get("/user/:id", (req, res) => {
  res.send("viewing " + req.user.name);
});

app.get("/user/:id/edit", (req, res) => {
  res.send("editing " + req.user.name);
});

app.put("/user/:id", (req, res) => {
  res.send("updating " + req.user.name);
});

app.get("*", (req, res) => {
  res.send("not found", 404);
});

app.listen(3000);

to add

app.get("*", (req, res) => {
  res.send("not found", 404);
});

at the end of the app to add a catch all route with a route handler that only runs when no other URLs listened above it is matched.

We call res.send to send a 404 response.

Conclusion

To get Express.js to send 404 only on missing routes, we can add a catch-all route at the end of the app.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *