In this lesson, you sent your plot board a POST it shouldn’t take, saw it answer 200 OK anyway, and moved its routes into a table so the board checks the path first, then the method.
Key Points
- Routing on the path alone ignores the method. Every branch compared
url.pathnameand neverreq.method, socurl -i -X POST http://localhost:3000/plotsgot200 OKand all 24 plots. APOSTasks a server to take something in, and the plot list takes nothing in, yet the200told the client itsPOSTworked. - A wrong path and a wrong method are two different misses.
404 Not Foundmeans no route has this path.405 Method Not Allowedmeans the path exists, but its routes don’t take this method, and the response’sAllowheader lists the methods they do take. - A method check in each branch’s condition isn’t enough. A wrong method would fall through to the fallback
404, and the board couldn’t tell a wrong path from a wrong method. - A route table keeps the method, the path, and the handler together.
type Routehas amethod, apath, and ahandler.type Handleris(res: ServerResponse, url: URL) => void. Each old branch’s code moves into a handler of its own:sendHello(),sendPlots(), andjoinWaitlist(). OnlysendPlots()needs the URL, and a function with fewer parameters still fits theHandlertype.ServerResponsecomes in withimport type. - The waiting list takes a
POST. Joining it sends in a name, so its row isPOST /waitlist. For now,joinWaitlist()still answers with the placeholder404until you build the waiting list. - The listener checks the path first.
routes.filter()keeps the matches, the routes whosepathisurl.pathname. With no matches, no route knows this path, sosendError()sends the404and the listener returns. - Then it checks the method.
matches.find()looks for the match whosemethodisreq.method, and givesundefinedwhen there’s none. Then the path exists but not for this method, so theAllowheader gets the matches’ methods, joined with", ", andsendError()sends a405in the error shape. - A route that matched on both answers. The listener calls
route.handler(res, url). - The query string doesn’t change the route. The path check compares the pathname without the query, so
GET /plots?vacant=truestill reachessendPlots()and gets200 OKwith plots 4, 13, and 20.
Asked again, the board answers GET /waitlist with 405 Method Not Allowed and Allow: POST, and POST /plots with a 405 and Allow: GET. So the rule is to match the path first, then the method: no route for the path gets a 404, a known path with the wrong method gets a 405 and an Allow header, and otherwise the route’s handler answers.