Reputation: 493
I'm trying to parse the url in node js. Getting null values from this code. It is receiving value for the path. But not for the host or protocol.,
var http = require('http');
var url = require('url');
http.createServer ( function (req,res){
var pathname = url.parse(req.url).pathname;
var protocol = url.parse(req.url).protocol;
var host = url.parse(req.url).host;
console.log("request for " + pathname + " recived.");
console.log("request for " + protocol + " recived.");
console.log("request for " + host + " recived.");
res.writeHead(200,{'Content-Type' : 'text/plain'});
res.write('Hello Client');
res.end();
}).listen(41742);
console.log('Server Running at port 41742');
console.log('Process IS :',process.pid);
Upvotes: 5
Views: 2802
Reputation: 79
you can view this source code: https://github.com/expressjs/express/blob/master/lib/request.js
Upvotes: 1
Reputation: 123423
The HTTP protocol doesn't communicate the combined URL in one value for Node to parse out.
A request to http://yourdomain.com/home
, for example, arrives as:
GET /home HTTP/1.1
Host yourdomain.com
# ... (additional headers)
So, the pieces won't all be in the same place.
The path and query-string you can get from the req.url
, as you were doing – it'll hold "/home"
for the above example.
var pathname = url.parse(req.url).pathname;
The host you can get from the req.headers
, though a value wasn't always required for it.
var hostname = req.headers.host || 'your-domain.com';
For the protocol, there isn't a standard placement for this value.
You can use the advice given in "How to know if a request is http or https in node.js" to determine between http
and https
.
var protocol = req.connection.encrypted ? 'https' : 'http';
Or, though it isn't standard, many clients/browsers will provide it with the X-Forwarded-Proto
header.
Upvotes: 3
Reputation: 2603
req.url
only contains the path not the entire url.
Rest are in request headers.
For Host: console.log(req.headers["host"]);
For Protocol: console.log(req.headers["x-forwarded-proto"]);
Upvotes: 1