The storefront and the API are two programs, and they need a contract: every answer of the API is JSON, and a failure is {"error": "…"} with a status that says what kind. Express does not know your contract. A path that no route matches gets its own HTML page, Cannot GET …, and a route that throws gets an HTML error page with status 500. The storefront's api() then calls response.json() on HTML, and the visitor reads Unexpected token '<'.
Express tries the routes and middlewares in the order they were added, so a middleware added after all the routes runs only when none of them answered. With a path in front, it only sees requests whose path starts with it. For a folder of files, it could look like this:
app.use("/files", (req, res) => {
res.status(404).send("No such file");
});
An error handler is a middleware with four parameters, (err, req, res, next). Express calls it only when something threw, and it knows it by the count, so all four must be there. It logs the details for the developer with console.error and gives the visitor a general message: an error's message can show table names, SQL or file paths.
Your app must answer:
GET /api/nope → 404 {"error": "Not found"}
GET /api/products/3 → 404 (the page shows: Not found)
POST /api/suggestions {"name": "Kettle"}, first time → 201
POST /api/suggestions {"name": "Kettle"}, second time → 500 (the form shows: Something went wrong)
Your task: in server/app.js, below the routes, add a middleware for /api paths that answers 404 with { error: "Not found" }, then an error handler with four parameters that logs the error and answers 500 with { error: "Something went wrong" }.
Assignment
Follow the Coding Tutorial to give the API's failures JSON answers: a 404 for unknown /api paths and a 500 error handler at the end of server/app.js.
Hint
Order matters: both go below the routes, just above module.exports. A middleware that neither answers nor calls next() leaves the request waiting forever.
Free plan: 30 tutor messages. PRO is unlimited.
