2

I have the following very simple code snippet in node.js (running under Windows 7)

var path = url.parse(req.url, true).pathname;
var href = url.parse(req.url, true).href;

console.log("path " + path + "\r\n");
console.log("href " + href + "\r\n");

I invoke the listener with localhost:8080/test

I would expect to see:

path /test
href /localhost:8080/test

Instead I get

path /test
href /test

Why is href not the the full url?

1
  • 1
    req.url only contains the path, that's why routes are matched as app.get('/test') Commented Dec 30, 2013 at 6:52

1 Answer 1

2

As @adeneo said in the comment, req.url only contains the path. There are two solutions, depending on whether you are using express or not.

If using express: You need to do the following:

var href = req.protocol + "://"+ req.get('Host') + req.url;
console.log("href " + href + "\r\n");

This wil output:

http://localhost:8080/test

Reference: http://expressjs.com/4x/api.html#req.get

If using node's http server: Use the request's headers:

var http = require('http');
http.createServer(function (req, res) {
  var href = "http://"+ req.headers.host + req.url;
  console.log("href " + href + "\r\n");
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

Reference: http://nodejs.org/api/http.html#http_message_headers

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

1 Comment

@ChrisG. That is a great point, and I certainly did not pay attention. Edit solves for both cases. Thanks!

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.