In this lesson, you asked your plot board for Mrs. Okafor’s most common call, the free plots, watched the request miss its branch, and parsed the URL so the board routes on the path and reads the query.
Key Points
req.urlis the whole request target. For requests like the ones in this lesson, such as/plots?vacant=true, it holds the path and the query string together, as one string. The listener loggedGET /plots?vacant=true, and the404message named the whole target,Nothing at /plots?vacant=true.- Comparing
req.urlwith a path misses any query string. The===operator compares the whole string, so"/plots?vacant=true"matches"/plots"up to the question mark and then keeps going. The request falls past every branch to the fallback, and that happens to any query string, on any path the board knows. - The
URLclass pulls the target apart, given a base. Passed"/plots?vacant=true"alone,new URL()throwsTypeError: Invalid URL, because a target like this one is a relative address, andURLcan’t read one without a base. The second argument,"http://localhost", is that base. It only fills in the parts the target is missing. Your routes never look at it, so it’s a stand-in. url.pathnameholds the path alone, andurl.searchParamsholds the query. For/plots?vacant=true,url.pathnameis"/plots", andurl.searchParams.get("vacant")gives the string"true". A name the query doesn’t have, such as"size", givesnull.- Everything in a URL arrives as text. A query value is always a string, or
nullwhen the name is missing, so the board comparesvacantwith the string"true". With no query,vacantisnull, and/plotssends the whole list as before. - The
?? "/"afterreq.urlis for the type check. Node.js’s types allowreq.urlto beundefined, so the??givesnpm run checka fallback of"/"that your server never uses. - A target that
URLcan’t parse gets a400. A badly broken target can still makenew URL()throw, and an error thrown in the listener stops the server. So the parse sits in atry, withurldeclared withletabove it so the branches below can still read it. Thecatchsends a400 Bad RequestwithsendError()and returns before any routing. - The fallback’s message still uses
req.url. The branches compareurl.pathname, but the404message names the whole target the client asked for, query string and all.
So the rule is to parse the URL once, route on its pathname, and read the query from searchParams, where every value comes back as a string, or as null when it’s missing.