new URL() - WHATWG URL API new URL() - WHATWG URL API javascript javascript

new URL() - WHATWG URL API


As Joshua Wise pointed out on Github (https://github.com/nodejs/node/issues/12682), the problem is that request.url is NOT an absolute URL. It can be used as a path or relative URL, but it is missing the host and protocol.

Following the API documentation, you can construct a valid URL by supplying a base URL as the second argument. This is still awkward because the protocol is not easily available from request.headers. I simply assumed HTTP:

var baseURL = 'http://' + request.headers.host + '/';var myURL = new URL(request.url, baseURL);

This is obviously not an ideal solution, but at least you can take advantage of the query string parsing. For example,

URL {  href: 'http://localhost:8080/?key1=value1&key2=value2',  origin: 'http://localhost:8080',  protocol: 'http:',  username: '',  password: '',  host: 'localhost:8080',  hostname: 'localhost',  port: '8080',  pathname: '/',  search: '?key1=value1&key2=value2',  searchParams: URLSearchParams { 'key1' => 'value1', 'key2' => 'value2' },  hash: '' }