1

I am sending data from JavaScript client to node.js server using XMLHttpRequest ajax. Now on server side I need to know the host of URL of the page the JavaScript calling XMLHttpRequest is embedded in.

Server side:

req.on('data', function(data) {
  var d = JSON.parse(data);
  if (d.Type == "abc") {
    var host = req.headers.Host;
    var reply = {
      "hostname": host
    };
    console.log("hostname :" + host);
    response.end(JSON.Stringify(reply));
  }
});

Expected result on console: hostname: hostname

Actual result on console: hostname: undefined

4
  • Kindly edit the post to add the full code if you have. Commented Dec 29, 2015 at 11:17
  • 3
    What is the question ? What is not working as you expect it to work ? Commented Dec 29, 2015 at 11:21
  • What do you mean by "client's url". Clients don't have URLs! Do you mean the hostname of the computer the request is coming from? Do you mean the URL of the page the JavaScript calling XMLHttpRequest is embedded in? Something else? Commented Dec 29, 2015 at 11:40
  • Yes @Quentin, i mean "client's url" as the second option suggested by you, thanks. Commented Dec 29, 2015 at 11:44

2 Answers 2

2

Browsers include a Referer HTTP Request header as normal for XHR requests. You can examine that.

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

1 Comment

Thanks @Quentin , referer works as var url=req.headers.referer gives full url and url.split("//")[2] gives domain name.
0

Try this

const clientUrl = req.header('Referer');
console.log(clientUrl);

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.