gumenimeda
gumenimeda

Reputation: 835

How to get HTTP header from Javascript?

I have a Tomcat server that only serves static files(html, css, js). When the request comes in it gets intercepted by a proxy server. Proxy server authenticates the user and adds a userId field to the header and forwards it my Tomcat server.

How can I access userId that has been stored in the header from javascript?

Thank you

Upvotes: 3

Views: 24175

Answers (2)

Pankaj Chauhan
Pankaj Chauhan

Reputation: 1715

Use below script for access userId

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
headers = req.getAllResponseHeaders().split("\n")
     .map(x=>x.split(/: */,2))
     .filter(x=>x[0])
     .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});

console.log(headers.userId);

Upvotes: 1

miguel-svq
miguel-svq

Reputation: 2176

You can't, BUT...

If such header is send to the browser you could make an ajax request and get that value from it.

This little javascript could be useful in your case. Watch out, use it with caution and sanitize or change the URL depending on your needs, this is just a "concept", not a copy-paste solution for every case. In many other cases this is not a valid solution, cause it is not the header of the loaded document, but another request. Anyway the server, content-type, etc can be use quite safely.

xmlhttp = new XMLHttpRequest();
xmlhttp.open("HEAD", document.URL ,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
  console.log(xmlhttp.getAllResponseHeaders());
  }
}
xmlhttp.send();

EDIT: Ooops, seem already anwser that part also... Accessing the web page's HTTP Headers in JavaScript Didn't read it all.

Upvotes: 5

Related Questions