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'
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With