Node: url.format ignores port

Created on 27 Mar 2017  路  8Comments  路  Source: nodejs/node

  • Version: v6.10.1
  • Platform: Windows 10 64bit
  • Subsystem: URL Module

Test code:

var url = require('url')
console.log(url.format({
    protocol: 'http',
    host: 'localhost',
    port: '8080'
}))

Output: http://localhost
Expected output: http://localhost:8080

url

Most helpful comment

No, but I can close it. Plus, it's useful for people searching for the same problem later.

All 8 comments

I think you want to specify hostname instead of host.

url.format({protocol: 'http', hostname: 'localhost', port: '8080'});
'http://localhost:8080'

Brainfart. @cjihrig That is absolutely correct. Now I'm wondering how come I couldn't see it. Sorry for littering, can you delete the issue?

No, but I can close it. Plus, it's useful for people searching for the same problem later.

I just went on a wild goosehunt bringing me to this issue, so thanks for not deleting it. Changing host to hostname magically made format() take port into consideration. Why would misspelling one property make format() ignore another?

``js var test = url.parse('http://localhost'); test.port = 8080; console.log(url.format(test)); ```` In this case the URL is parsed, hencehost/hostnameshould be correctly set by the url parser? Changing the port doesn't work. Must thehostproperty be set to null before usingformat()` for setting the port?

@asbjornu it's because of this - if you set host, it "overwrites" port, because host is hostname+port

@FyiurAmron, that makes sense. Thanks for pointing it out!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

danielstaleiny picture danielstaleiny  路  3Comments

ksushilmaurya picture ksushilmaurya  路  3Comments

vsemozhetbyt picture vsemozhetbyt  路  3Comments

mcollina picture mcollina  路  3Comments

stevenvachon picture stevenvachon  路  3Comments