如何从 Javascript 获取 HTTP 标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24044346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:03:29  来源:igfitidea点击:

How to get HTTP header from Javascript?

javascripthtmlproxyhttp-headers

提问by gumenimeda

I have a Tomcat server that only serves static files(html, css, js). When the request comes in it gets intercepted by a proxy server. Proxy server authenticates the user and adds a userIdfield to the header and forwards it my Tomcat server.

我有一个只提供静态文件(html、css、js)的 Tomcat 服务器。当请求进来时,它会被代理服务器拦截。代理服务器对用户进行身份验证并向userId标头添加一个 字段并将其转发到我的 Tomcat 服务器。

How can I access userIdthat has been stored in the header from javascript?

如何userId从javascript访问已存储在标头中的内容?

Thank you

谢谢

回答by miguel-svq

You can't, BUT...

你不能,但是……

If such header is send to the browser you could make an ajax request and get that value from it.

如果将此类标头发送到浏览器,您可以发出 ajax 请求并从中获取该值。

This little javascript could be useful in your case. Watch out, use it with caution and sanitize or change the URL depending on your needs, this is just a "concept", not a copy-paste solution for every case. In many other cases this is not a valid solution, cause it is not the header of the loaded document, but another request. Anyway the server, content-type, etc can be use quite safely.

这个小 javascript 可能对您有用。注意,谨慎使用它并根据您的需要清理或更改 URL,这只是一个“概念”,而不是适用于所有情况的复制粘贴解决方案。在许多其他情况下,这不是一个有效的解决方案,因为它不是加载文档的标题,而是另一个请求。无论如何,服务器、内容类型等都可以非常安全地使用。

xmlhttp = new XMLHttpRequest();
xmlhttp.open("HEAD", document.URL ,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
  console.log(xmlhttp.getAllResponseHeaders());
  }
}
xmlhttp.send();

EDIT: Ooops, seem already anwser that part also... Accessing the web page's HTTP Headers in JavaScriptDidn't read it all.

编辑:哎呀,似乎也已经回答了那部分...在 JavaScript 中访问网页的 HTTP 标头没有全部阅读。

回答by Pankaj Chauhan

Use below script for access userId

使用以下脚本访问 userId

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
headers = req.getAllResponseHeaders().split("\n")
     .map(x=>x.split(/: */,2))
     .filter(x=>x[0])
     .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});

console.log(headers.userId);