EasyJavaScriptTypeScript
Node.js — Parse a Request URL
Node.jsBackendURLHTTP
When a browser asks tinyserve for a file, Node hands over req.url: only the path and the query
string, still percent-encoded — '/files/report%20v2.pdf?download=1'. Before looking for a
file, the server needs the real path (/files/report v2.pdf) and the parameters.
Your task
Write parseRequestTarget(target) with the WHATWG
[`URL`](https://nodejs.org/api/url.html#the-whatwg-url-api) class and its searchParams.
Return { path, params }:
path— the pathname, percent-decoded withdecodeURIComponent.params— one key per query parameter. A parameter that appears once maps to its string;
one that appears several times maps to the array of its values, in order. + means a space.
- The fragment (
#...) is not part of either.
If the path contains a broken escape (%E0%A4%A, a lone %), decodeURIComponent throws aURIError: return { error: 'Bad Request' } — a server answers 400, it does not crash.
Example
parseRequestTarget('/search?q=node+streams&tag=io&tag=fs');
// → { path: '/search', params: { q: 'node streams', tag: ['io', 'fs'] } }Sample tests
Test #1Root
Input: ["/"]
Output: {"path":"/","params":{}}
Test #2Encoded space and one parameter
Input: ["/files/report%20v2.pdf?download=1"]
Output: {"path":"/files/report v2.pdf","params":{"download":"1"}}
Test #3Plus sign and repeated key
Input: ["/search?q=node+streams&tag=io&tag=fs"]
Output: {"path":"/search","params":{"q":"node streams","tag":["io","fs"]}}
Test #4Broken escape
Input: ["/bad%E0%A4%A"]
Output: {"error":"Bad Request"}