5

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);
Akhilesh Singh
  • 1,724
  • 2
  • 19
  • 35
Asanka
  • 483
  • 2
  • 8
  • 21
  • Can you give us an example of a URL that doesn't work, and also have you console logged req.url? – anthonygore Apr 13 '16 at 04:12
  • The HTTP protocol doesn't communicate the combined URL in one value for Node to parse out. Only the path and optional query-string are given in `req.url` (for a `GET /foo` request, `req.url === "/foo"`). The `Host` is in a request header, at least in HTTP 1.1 and later. – Jonathan Lonowski Apr 13 '16 at 04:18
  • So how do I print the host and protocol ? Thanks – Asanka Apr 13 '16 at 04:21

3 Answers3

3

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.

Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
1

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"]);

Nivesh
  • 2,573
  • 1
  • 20
  • 28
1

you can view this source code: https://github.com/expressjs/express/blob/master/lib/request.js

Frog Tan
  • 79
  • 4