Your routes send errors as JSON. But when a path has no route at all, like /contact, none of your code answers: Express answers by itself, with a 404 page in HTML. A browser can show it, but a program that expects JSON can't read it.
Express lets you replace that page with a function of your own. Express tries your routes from top to bottom, in the order they are written. A function you give to app.use with no path takes every request that gets as far as its line, whatever the method or the path. Put it at the very end of the file, and it only gets the requests no route answered. Here is one in another app, a blog (not part of this lesson):
blog.get("/posts", (req, res) => {
res.json(posts);
});
function noSuchPage(req, res) {
res.status(404).send("No such page");
}
blog.use(noSuchPage);
Your function only gets what the routes leave behind. A route that sends its own 404, like the one for one product, answers first and keeps its message. A wrong method on a known path is still answered by the shop's app.all routes, with 405 and their HTML page. And /products/abc reaches your function too, because the product routes pass it on with next(). The requests and answers your code must give, in this order:
GET /contact → 404 {"error": "Not found"}
GET /products/abc → 404 {"error": "Not found"}
POST /orders {"product_id": 1, "quantity": 2} → 404 {"error": "Not found"}
GET /products/9 → 404 {"error": "Product not found"}
DELETE /products → 405 (the shop's HTML page, as before)
GET /about → 200 {"name": "Corner Shop", "currency": "USD"}
Your task: write a function notFound(req, res) that answers {"error": "Not found"} with status 404 through your errorResponse helper, and give it to Express with app.use as the last line of the file.
Assignment
Follow the Coding Tutorial to answer unknown paths with a 404 in JSON.
Hint
Write notFound without parentheses inside app.use(...): you pass the function itself, and Express calls it. The line must come after every route: a route written below it would never get a request.
Free plan: 30 tutor messages. PRO is unlimited.
