Accessing the web page's HTTP Headers in JavaScript

前端 未结 17 2615
日久生厌
日久生厌 2020-11-21 04:53

How do I access a page\'s HTTP response headers via JavaScript?

Related to this question, which was modified to ask about accessing two specific HTTP headers.

<
17条回答
  •  误落风尘
    2020-11-21 05:42

    Like many people I've been digging the net with no real answer :(

    I've nevertheless find out a bypass that could help others. In my case I fully control my web server. In fact it is part of my application (see end reference). It is easy for me to add a script to my http response. I modified my httpd server to inject a small script within every html pages. I only push a extra 'js script' line right after my header construction, that set an existing variable from my document within my browser [I choose location], but any other option is possible. While my server is written in nodejs, I've no doubt that the same technique can be use from PHP or others.

      case ".html":
        response.setHeader("Content-Type", "text/html");
        response.write ("")
        // process the real contend of my page
    

    Now every html pages loaded from my server, have this script executed by the browser at reception. I can then easily check from JavaScript if the variable exist or not. In my usecase I need to know if I should use JSON or JSON-P profile to avoid CORS issue, but the same technique can be used for other purposes [ie: choose in between development/production server, get from server a REST/API key, etc ....]

    On the browser you just need to check variable directly from JavaScript as in my example, where I use it to select my Json/JQuery profile

     // Select direct Ajax/Json profile if using GpsdTracking/HttpAjax server otherwise use JsonP
      var corsbypass = true;  
      if (location['GPSD_HTTP_AJAX']) corsbypass = false;
    
      if (corsbypass) { // Json & html served from two different web servers
        var gpsdApi = "http://localhost:4080/geojson.rest?jsoncallback=?";
      } else { // Json & html served from same web server [no ?jsoncallback=]
        var gpsdApi = "geojson.rest?";
      }
      var gpsdRqt = 
          {key   :123456789 // user authentication key
          ,cmd   :'list'    // rest command
          ,group :'all'     // group to retreive
          ,round : true     // ask server to round numbers
       };
       $.getJSON(gpsdApi,gpsdRqt, DevListCB);
    

    For who ever would like to check my code: https://www.npmjs.org/package/gpsdtracking

提交回复
热议问题