Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js url.parse only returns null for host and protocol

Tags:

url

node.js

I'm just getting started with node.js. According to https://www.npmjs.org/package/url url_parts should have the keys host and protocol. However both only return null. Why?

I'm calling the server with http://localhost:8181/test/?var=vartest

http.createServer(function(req, res) {
    var url_parts = url.parse(req.url,true);
    console.log(url_parts);
    ...
}.listen(8181);

and the console log:

{ protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?var=vartest',
  query: { var: 'vartet' },
  pathname: '/test/',
  path: '/test/?var=vartest',
  href: '/test/?var=vartest'
}
like image 725
Manuel Avatar asked Jul 28 '14 23:07

Manuel


1 Answers

You can get what you want with this code:

http.createServer(function(req, res) {
    var realUrl = (req.connection.encrypted ? 'https': 'http') + '://' + req.headers.host + req.url;
    var url_parts = url.parse(realUrl,true);
    console.log(url_parts);
    ...
}).listen(8181)

req.url just returns path, You should detect host and protocol separately.

like image 141
Alireza Ahmadi Avatar answered Oct 15 '22 15:10

Alireza Ahmadi