简体   繁体   English

使用 JavaScript 添加自定义 HTTP 标头

[英]Adding custom HTTP headers using JavaScript

On an HTML page, while clicking the link of an Image ("img") or anchor ("a") tags, I would like to add custom headers for the GET request.在 HTML 页面上,单击图像(“img”)或锚点(“a”)标签的链接时,我想为 GET 请求添加自定义标头。 These links are typically for downloading dynamic content.这些链接通常用于下载动态内容。 These headers could be SAML headers or custom application specific headers.这些标头可以是 SAML 标头或自定义应用程序特定标头。

Is it possible to add these custom headers through JavaScript?是否可以通过 JavaScript 添加这些自定义标头? Or if I add these through XMLHttpRequest, how can I achieve the download functionality?或者如果我通过XMLHttpRequest添加这些,如何实现下载功能?

This requirement is for IE6 or 7 only.此要求仅适用于 IE6 或 7。

If you're using XHR , then setRequestHeader should work, eg如果您使用的是XHR ,那么setRequestHeader应该可以工作,例如

xhr.setRequestHeader('custom-header', 'value');

PS You should use Hijax to modify the behavior of your anchors so that it works if for some reason the AJAX isn't working for your clients (like a busted script elsewhere on the page). PS 你应该使用Hijax来修改你的锚的行为,这样如果由于某种原因 AJAX 对你的客户不起作用(就像页面上其他地方的破坏脚本),它就可以工作。

I think the easiest way to accomplish it is to use querystring instead of HTTP headers.我认为完成它的最简单方法是使用查询字符串而不是 HTTP 标头。

The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method.从浏览器内部向请求添加标头的唯一方法是使用 XmlHttpRequest setRequestHeader 方法。

Using this with "GET" request will download the resource.将此与“GET”请求一起使用将下载资源。 The trick then is to access the resource in the intended way.那么诀窍就是以预期的方式访问资源。 Ostensibly you should be able to allow the GET response to be cacheable for a short period, hence navigation to a new URL or the creation of an IMG tag with a src url should use the cached response from the previous "GET".从表面上看,您应该能够允许 GET 响应在短时间内缓存,因此导航到新的 URL 或创建带有 src url 的 IMG 标签应该使用来自先前“GET”的缓存响应。 However that is quite likely to fail especially in IE which can be a bit of a law unto itself where the cache is concerned.但是,这很可能会失败,尤其是在 IE 中,这在涉及缓存的情况下可能有点自成一格。

Ultimately I agree with Mehrdad, use of query string is easiest and most reliable method.最终我同意 Mehrdad,使用查询字符串是最简单和最可靠的方法。

Another quirky alternative is use an XHR to make a request to a URL that indicates your intent to access a resource.另一个古怪的选择是使用 XHR 向 URL 发出请求,表明您打算访问资源。 It could respond with a session cookie which will be carried by the subsequent request for the image or link.它可以使用 session cookie 进行响应,该 cookie 将由后续的图像或链接请求携带。

As already said, the easiest way is to use querystring.如前所述,最简单的方法是使用查询字符串。

But if you cannot, because of security reason, you should consider using cookies.但是如果你不能,出于安全原因,你应该考虑使用 cookies。

In 2021, this can be accomplished with Service Workers .在 2021 年,这可以通过Service Workers来实现。

First, you have to register a Service Worker on your page.首先,您必须在您的页面上注册一个 Service Worker。

// index.html
window.addEventListener('load', function () {
    navigator
        .serviceWorker
        .register('/service-worker.js');
});

In the Service Worker a request is captured, modified and forwarded by calling the WindowOrWorkerGlobalScope.fetch() method.在 Service Worker 中,通过调用WindowOrWorkerGlobalScope.fetch()方法来捕获、修改和转发请求。

// service-worker.js
self.addEventListener('fetch', function (event) {
    event.respondWith(async function () {
        let headers = new Headers()
        headers.append("X-Custom-Header", "Random value")
        return fetch(event.request, {headers: headers})
    }());
});

Please note that some web browsers does not show modified requests in the developer console.请注意,某些 web 浏览器不会在开发者控制台中显示修改后的请求。 In that case requests can be observed with tools like tcpdump, Wireshark or in a server's logs.在这种情况下,可以使用 tcpdump、Wireshark 等工具或在服务器日志中观察请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM