Each route answers one method on one path. When a request comes for a path that exists, but with a method no route handles, Express answers with its 404 page, as if the path did not exist. The clear answer is 405 Method Not Allowed, with an Allow header: the list of methods the path does accept. A path with no route at all still gets 404 Not Found.
Express doesn't send a 405 by itself, so you write it. A route made with app.all matches every method. Express tries the routes from top to bottom, so when it sits below a path's other routes, only the methods they don't answer reach it. For a path with only a GET route, it could look like this (not part of the shop):
app.get("/notes", (req, res) => {
res.json(notes);
});
app.all("/notes", (req, res) => {
res.set("Allow", "GET, HEAD, OPTIONS");
res.status(405).send("Method Not Allowed");
});
HEAD is a GET without the body, and OPTIONS is the method a client uses to ask what a path allows; both belong in the list. The shop's starting code already answers 405 this way for /products and for a product's own path.
Now you'll do it for /about. Its answer used to be written inside the route, so nothing could change it. You'll keep the shop's details in an object shop that both routes share, add a PUT route that replaces them, and answer 405 for every other method. The requests and answers your code must give, in this order:
PUT /products {"name": "Cup", "price": 5, "category": "kitchen"}
→ 405 Allow: GET, HEAD, OPTIONS, POST
POST /products/2 {"price": 5}
→ 405 Allow: DELETE, GET, HEAD, OPTIONS, PATCH, PUT
DELETE /about → 405 Allow: GET, HEAD, OPTIONS, PUT
PUT /about {"name": "Corner Store", "currency": "EUR"}
→ 200 {"name": "Corner Store", "currency": "EUR"}
GET /about → 200 {"name": "Corner Store", "currency": "EUR"}
GET /contact → 404
Your task: keep the about details in an object shop, make GET /about answer it, and add PUT /about, which replaces the name and currency with the ones in the body and answers the new details. Then add an app.all route for /about that answers 405 with Allow: GET, HEAD, OPTIONS, PUT for every other method.
Assignment
Follow the Coding Tutorial to store the shop's details in a constant, add a PUT route for /about and answer 405 for the methods it doesn't allow.
Hintshop lives outside the routes, so both routes read and change the same object. The app.all route for /about goes below its GET and PUT routes: Express tries the routes from top to bottom, so only the other methods reach it.
Free plan: 30 tutor messages. PRO is unlimited.
