-
- Notifications
You must be signed in to change notification settings - Fork 33.8k
Closed
Description
- Version: all
- Platform: all
- Subsystem: url
In docs there is incorrect example of code: https://nodejs.org/api/http.html#http_message_url
Here is a quote from the documentation
START OF QUOTE
To parse the URL into its parts:
new URL(request.url, `http://${request.headers.host}`);When request.url is '/status?name=ryan' and
request.headers.host is 'localhost:3000':
$ node > new URL(request.url, request.headers.host) URL { href: 'http://localhost:3000/status?name=ryan', origin: 'http://localhost:3000', protocol: 'http:', username: '', password: '', host: 'localhost:3000', hostname: 'localhost', port: '3000', pathname: '/status', search: '?name=ryan', searchParams: URLSearchParams { 'name' => 'ryan' }, hash: '' }END OF QUOTE
The first code example is right. To parse request.url from localhost you need to use it:
new URL(request.url, `http://${request.headers.host}`);But in the next code example new URL('/status?name=ryan', 'localhost:3000') resolves with URL Object, but it is incorrect behaviour. In real life it throws error
$ node > new URL('/status?name=ryan', 'localhost:3000') Uncaught TypeError [ERR_INVALID_URL]: Invalid URL: /status?name=ryan at onParseError (internal/url.js:257:9) at new URL (internal/url.js:333:5) at repl:1:1 at Script.runInThisContext (vm.js:120:20) at REPLServer.defaultEval (repl.js:427:29) at bound (domain.js:429:14) at REPLServer.runBound [as eval] (domain.js:442:12) at REPLServer.onLine (repl.js:754:10) at REPLServer.emit (events.js:333:22) at REPLServer.EventEmitter.emit (domain.js:485:12) { input: '/status?name=ryan', code: 'ERR_INVALID_URL' }So the second code example should be:
$ node > new URL(request.url, `http://${request.headers.host}`) URL { href: 'http://localhost:3000/status?name=ryan', origin: 'http://localhost:3000', protocol: 'http:', username: '', password: '', host: 'localhost:3000', hostname: 'localhost', port: '3000', pathname: '/status', search: '?name=ryan', searchParams: URLSearchParams { 'name' => 'ryan' }, hash: '' }Code example: https://repl.it/@NMVikings/URL
Metadata
Metadata
Assignees
Labels
No labels