Search code examples
javascriptnginxheaderhtml-helper

Printing the web page's HTTP Headers using JavaScript


So I have a webapp that is built on the nodejs framework. At the moment I am using an NGINX Reverse Proxy that uses OIDC for authentication. Once the user is authenticated it then forwards them on to the nodejs backend.

I want to grab the users email address from the header which is passed from the reverse proxy to the backend and print it on my homepage so it will say Welcome XXX

Now I can see that if i add the below in my app.js it will print the headers to the command line so i know it is being passed, but i just do not what javascript i need to achieve this

app.get('/home', function (req) {
  console.log(req.headers);
});

The example found here Accessing the web page's HTTP Headers in JavaScript does present me with a popup but it does not grab show the info i need which is 'x-user': 'fffffff@ffff.fff'

I tried this code also but it is not picking it up for me

<script>
function getClientIP(req){
    return req.headers['x-user'];
}
</script>
<h3><b><script>getClientIP();</script></b></h3>

I have this printing to the console.log so i know for a fact x-user is present in the request.


Solution

  • Figured it out

        <script>
        function parseHttpHeaders(httpHeaders) {
            return httpHeaders.split("\n")
             .map(x=>x.split(/: */,2))
             .filter(x=>x[0])
             .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
        }
        var req = new XMLHttpRequest();
        req.open('HEAD', document.location, false);
        req.send(null);
        var headers = parseHttpHeaders(req.getAllResponseHeaders());
        </script>
    
        <script>
        function here() {
         document.write(JSON.stringify(headers["x-user"]));
        }
        </script>
    
    
    <h3><b><script>here();</script></b></h3>