Reputation: 39
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?
Upvotes: 2
Views: 3355
Reputation: 5804
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
Upvotes: 2