如何通过JavaScript访问页面的HTTP响应头?
与此问题相关,该问题已被修改为询问访问两个特定的HTTP报头。
相关: 如何通过JavaScript访问HTTP请求报头字段?
如何通过JavaScript访问页面的HTTP响应头?
与此问题相关,该问题已被修改为询问访问两个特定的HTTP报头。
相关: 如何通过JavaScript访问HTTP请求报头字段?
当前回答
为了获得头部作为一个更方便的对象(改进Raja的答案):
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;
}, {});
其他回答
向JavaScript发送报头信息的另一种方法是通过cookie。服务器可以从请求头中提取它需要的任何数据,并将它们发送回Set-Cookie响应头中——并且cookie可以在JavaScript中读取。但是,正如keparo所说,最好只对一个或两个头文件执行此操作,而不是对所有头文件执行此操作。
和许多人一样,我一直在网上搜索,没有真正的答案:(
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 ("<script>location['GPSD_HTTP_AJAX']=true</script>")
// process the real contend of my page
现在每一个html页面加载从我的服务器,有这个脚本执行的浏览器在接收。然后,我可以很容易地从JavaScript检查变量是否存在。在我的用例中,我需要知道我是否应该使用JSON或JSON- p配置文件来避免CORS问题,但同样的技术可以用于其他目的[即:在开发/生产服务器之间选择,从服务器获取REST/API密钥等....]
在浏览器上,你只需要直接从JavaScript检查变量,在我的例子中,我用它来选择我的Json/JQuery配置文件
// 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);
对于任何想要检查我代码的人: https://www.npmjs.org/package/gpsdtracking
如前所述,如果您控制服务器端,那么应该可以在初始响应中将初始请求头发送回客户端。
以Express为例,以下工作:
App.get ('/somepage', (req, res) => { res.render(“somepage。Hbs ', {headers: req.headers}); }) 然后在模板中可以使用头文件,因此可以在视觉上隐藏,但包含在标记中并由客户端javascript读取。
Allain Lalonde的链接让我很开心。 只是在这里添加了一些简单的html代码。 适用于任何合理的浏览器,年龄加上IE9+和preto - opera 12。
<!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>
注意:你得到第二个请求的头,结果可能不同于最初的请求。
另一种方法是更现代的fetch() API https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch 根据caniuse.com, Firefox 40, Chrome 42, Edge 14, Safari 11都支持它 工作示例代码:
<!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>
如果我们讨论的是请求标头,您可以在执行xmlhttprequest时创建自己的标头。
var request = new XMLHttpRequest();
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.open("GET", path, true);
request.send(null);