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);
3
  • Can you give us an example of a URL that doesn't work, and also have you console logged req.url? Commented Apr 13, 2016 at 4: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. Commented Apr 13, 2016 at 4:18
  • So how do I print the host and protocol ? Thanks Commented Apr 13, 2016 at 4:21

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.