Search code examples
javascripturlhttpsport

Why does javascript ignore the port of an url-string when creating the url-Object?


I want to read the port of an string of an url I have. I found out that you can create a new URL-object with the urlstring as an argument. Then you can call the port property of that object to get the port of the urlstring.

The port of my url is 443. If I give a string with 443 as the port into the URL-object, the port-property of the url-object is "". If I choose other numbers as the port it works fine.

Does anyone know why this is happening?

Here is a code-snippet:

const URL_STRING1 = "https://example.com:443/";

let url1 = new URL(URL_STRING1);
console.log(url1.port);

const URL_STRING2 = "https://example.com:442/";

let url2 = new URL(URL_STRING2);
console.log(url2.port);

const URL_STRING3 = "https://example.com:444/";

let url3 = new URL(URL_STRING3);
console.log(url3.port);


Solution

  • 443 is default port for https

    URL reference for full specs

    ....
    --->   Set url’s port to null, if port is url’s scheme’s default port, and to port otherwise.
                                                    ^^^^^^^^^^^^^^^^^^^^^
    ....
    

    Default scheme reference for full specs

    A special scheme is a scheme listed in the first column of the following table. A default port is a special scheme’s optional corresponding port and is listed in the second column on the same row.
    
    scheme  port
    "ftp"   21
    "file"  
    "http"  80
    "https"     443
    "ws"    80
    "wss"   443