Http headers in Javascript?

喜你入骨 提交于 2019-12-10 18:16:46

问题


Is it possible to gather the HTTP headers in JavaScript ? This is just a thought of mine after using Firebug for days. In one of the posts I came to know that, it is impossible to find the HTTP headers in JavaScript, whereas in firebug, we can see the response headers (client side)

so my question is can we cache the HTTP headers in JavaScript ?


回答1:


The HTTP headers aren't available in JavaScript.

However you could use XMLHttpRequest to do a HEAD request to any resource within the same domain:

var xhr = new XMLHttpRequest();

xhr.open('HEAD', '/', true);            // Relative path of resource

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    console.log(xhr.getAllResponseHeaders());
  }
}

xhr.send(null);

The above will return something like this (running it in Firebug on this page):

Server: nginx 
Date: Fri, 09 Jul 2010 18:58:30 GMT 
Content-Type: text/html; charset=utf-8 
Connection: keep-alive 
Cache-Control: public, max-age=60 
Content-Length: 33273 
Content-Encoding: gzip 
Expires: Fri, 09 Jul 2010 18:59:31 GMT 
Last-Modified: Fri, 09 Jul 2010 18:58:31 GMT 
Vary: * 

You can easily get the value of single headers like this:

xhr.getResponseHeader('Last-Modified');



回答2:


Firebug is not a web application - it is a XUL application (that is, a Mozilla application, written with XUL and javascript) and as such has access to http headers that browser side javascript cannot access.

You cannot access http header via javascript in the browser.



来源:https://stackoverflow.com/questions/3215613/http-headers-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!