Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问网页';JavaScript中的HTTP头_Javascript_Http_Http Headers - Fatal编程技术网

访问网页';JavaScript中的HTTP头

访问网页';JavaScript中的HTTP头,javascript,http,http-headers,Javascript,Http,Http Headers,如何通过JavaScript访问页面的HTTP响应头 与相关,它被修改为询问如何访问两个特定的HTTP头 相关: 不幸的是,没有API为您的初始页面请求提供HTTP响应头。这是张贴在这里的原始问题。这也是因为有些人希望在不发出另一个响应头的情况下获得原始页面请求的实际响应头 对于AJAX请求: 如果通过AJAX发出HTTP请求,则可以使用getAllResponseHeaders()方法获取响应头。它是XMLHttpRequestAPI的一部分。要了解如何应用此功能,请查看下面的fetchSi

如何通过JavaScript访问页面的HTTP响应头

与相关,它被修改为询问如何访问两个特定的HTTP头

相关:


不幸的是,没有API为您的初始页面请求提供HTTP响应头。这是张贴在这里的原始问题。这也是因为有些人希望在不发出另一个响应头的情况下获得原始页面请求的实际响应头


对于AJAX请求: 如果通过AJAX发出HTTP请求,则可以使用
getAllResponseHeaders()
方法获取响应头。它是XMLHttpRequestAPI的一部分。要了解如何应用此功能,请查看下面的
fetchSimilarHeaders()
函数。请注意,这是解决某些应用程序不可靠的问题的方法

myXMLHttpRequest.getAllResponseHeaders();
  • 以下XMLHttpRequest候选建议中指定了API:

  • 具体而言,以下部分指定了
    getAllResponseHeaders()
    方法:

  • MDN文档也很好:

这不会为您提供有关原始页面请求的HTTP响应头的信息,但可以使用它对这些头是什么进行有根据的猜测。关于这一点的更多信息将在下面介绍


从初始页面请求获取标题值: 这个问题在几年前首次提出,专门询问如何获取当前页面(即运行javascript的同一页面)的原始HTTP响应头。这与简单地获取任何HTTP请求的响应头是完全不同的问题。对于初始页面请求,javascript不容易获得标题。如果通过AJAX再次请求相同的页面,则所需的标题值是否可靠且充分一致将取决于您的特定应用程序

下面是一些解决这个问题的建议


1。对基本上是静态的资源的请求 如果响应基本上是静态的,并且请求之间的头不会有太大变化,那么您可以对当前所在的同一页面发出AJAX请求,并假设它们是相同的值,这些值是页面HTTP响应的一部分。这允许您使用上面描述的漂亮的XMLHttpRequestAPI访问所需的头

function fetchSimilarHeaders (callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE) {
            //
            // The following headers may often be similar
            // to those of the original page request...
            //
            if (callback && typeof callback === 'function') {
                callback(request.getAllResponseHeaders());
            }
        }
    };

    //
    // Re-request the same page (document.location)
    // We hope to get the same or similar response headers to those which 
    // came with the current page, but we have no guarantee.
    // Since we are only after the headers, a HEAD request may be sufficient.
    //
    request.open('HEAD', document.location, true);
    request.send(null);
}
如果您确实必须依赖于请求之间的值是一致的,那么这种方法将是有问题的,因为您不能完全保证它们是相同的。这将取决于您的特定应用程序,以及您是否知道您所需要的值是不会从一个请求更改到下一个请求的


2。推论 有一些BOM表属性(浏览器对象模型),浏览器通过查看标题来确定这些属性。其中一些属性直接反映HTTP头(例如,
navigator.userAgent
设置为HTTP
User Agent
头字段的值)。通过嗅探可用的属性,您可能能够找到您需要的内容,或者找到一些指示HTTP响应所包含内容的线索


3。藏起来
如果您控制服务器端,则可以在构造完整响应时访问任何您喜欢的头。值可以与页面一起传递给客户机,存储在一些标记中,或者可能存储在内联JSON结构中。如果希望javascript可以使用每个HTTP请求头,可以在服务器上迭代它们,并将它们作为标记中的隐藏值发送回。以这种方式发送头值可能不太理想,但您当然可以针对所需的特定值进行发送。这个解决方案也可能效率低下,但如果您需要它,它可以完成这项工作。

另一种向JavaScript发送头信息的方法是通过cookies。服务器可以从请求头中提取它需要的任何数据,并将它们发送回
Set Cookie
响应头中,并且Cookie可以用JavaScript读取。但是,正如keparo所说,最好只对一个或两个头执行此操作,而不是对所有头执行此操作。

如果我们讨论的是请求头,则可以在执行XmlHttpRequests时创建自己的头

var request = new XMLHttpRequest();
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.open("GET", path, true);
request.send(null);

使用
XmlHttpRequest
可以调出当前页面,然后检查响应的http头

最好的情况是只做一个
HEAD
请求,然后检查header

有关执行此操作的一些示例,请参见


只有我的2美分。

使用mootools,您可以使用这个.xhr.getAllResponseHeaders()

这是一个老问题。不确定何时支持变得更广泛,但是
getAllResponseHeaders()
getResponseHeader()
现在看起来相当标准:

无法读取当前标题。您可以对同一URL发出另一个请求并读取其标题,但不能保证标题与当前URL完全相同


通过执行
get
请求,使用以下JavaScript代码获取所有HTTP头:

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);

您无法访问http头,但其中提供的一些信息在DOM中可用。例如,如果您想查看http引用器(sic),请使用document.referer。对于其他http头,可能还有其他类似的情况。试着用谷歌搜索你想要的特定内容,比如“http referer javascript”


我知道这应该是显而易见的,但我一直在搜索“http头javascript”之类的东西,而我真正想要的只是引用程序,没有得到任何有用的结果。我不知道我怎么会没有意识到我可以做一个更具体的查询。

我刚刚测试过,这对我使用Chrome版本28.0.1500.95是有效的

var xhr = new XMLHttpRequest(); 
xhr.open('POST', url, true); 
xhr.responseType = "blob";
xhr.onreadystatechange = function () { 
    if (xhr.readyState == 4) {
        success(xhr.response); // the function to proccess the response

        console.log("++++++ reading headers ++++++++");
        var headers = xhr.getAllResponseHeaders();
        console.log(headers);
        console.log("++++++ reading headers end ++++++++");

    }
};
Date: Fri, 16 Aug 2013 16:21:33 GMT
Content-Disposition: attachment;filename=testFileName.doc
Content-Length: 20
Server: Apache-Coyote/1.1
Content-Type: application/octet-stream
  case ".html":
    response.setHeader("Content-Type", "text/html");
    response.write ("<script>location['GPSD_HTTP_AJAX']=true</script>")
    // process the real contend of my page
 // 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);
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('GET', document.location, false);
req.send(null);
var headers = parseHttpHeaders(req.getAllResponseHeaders());
// Now we can do:  headers["content-type"]
var url = "< URL >";

var req = new XMLHttpRequest();
req.open('HEAD', url, false);
req.send(null);
var headers = req.getAllResponseHeaders();

//Show alert with response headers.
alert(headers);
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
headers = headers.split(/\n|\r|\r\n/g).reduce(function(a, b) {
    if (b.length) {
        var [ key, value ] = b.split(': ');
        a[key] = value;
    }
    return a;
}, {});
console.log(headers);
<!DOCTYPE html>
<title>(XHR) Show all response headers</title>

<h1>All Response Headers with XHR</h1>
<script>
 var X= new XMLHttpRequest();
 X.open("HEAD", location);
 X.send();
 X.onload= function() { 
   document.body.appendChild(document.createElement("pre")).textContent= X.getAllResponseHeaders();
 }
</script>
<!DOCTYPE html>
<title>fetch() all Response Headers</title>

<h1>All Response Headers with fetch()</h1>
<script>
 var x= "";
 if(window.fetch)
    fetch(location, {method:'HEAD'})
    .then(function(r) {
       r.headers.forEach(
          function(Value, Header) { x= x + Header + "\n" + Value + "\n\n"; }
       );
    })
    .then(function() {
       document.body.appendChild(document.createElement("pre")).textContent= x;
    });
 else
   document.write("This does not work in your browser - no support for fetch API");
</script>
server-timing: key;desc="value"
server-timing: key1;desc="value1"
server-timing: key2;desc="value2"
server-timing: key1;desc="value1", key2;desc="value2"