javascript - 在 Javascript 中为所有 http 请求添加自定义标头
问题描述
我想为 ASP.Net Web 窗体应用程序中的每个 http 调用添加自定义标头(承载令牌)。
使用以下链接中的建议,我添加了将添加的标头发送到服务器的代码,但无济于事。
和
<script>
(function() {
(function (open) {
XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
console.log("Adding header");
open.call(this, method, url, async, user, password);
this.setRequestHeader("X-Hello", "There " + new Date());
};
})(XMLHttpRequest.prototype.open);
})();
</script>
和
<script>
(function() {
(function (send) {
XMLHttpRequest.prototype.send = function (data) {
console.log("Adding header");
this.setRequestHeader("X-Hello", "There");
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
})();
</script>
我知道该解决方案应该仅适用于 POST(但它不适用。)我确实看到了每个帖子的 console.log,但标题“X-Hello”从未显示在服务器端。
使用服务工作者的长期解决方案失败了:
return Promise.resolve(new Request(data.url, data));
“无法构造‘请求’:无法使用模式为‘导航’且非空 RequestInit 的请求构造请求。”
解决方案
一种方法是使用服务工作者。但是,并非所有浏览器都支持此方法,因此请注意您的观众。使用服务工作者,您将拦截通过浏览器的所有获取请求。但是,浏览器只允许您为与当前来源相关的 url 发送自定义标头。考虑到这一点,这里有一个代码示例。
//This is the fetch event listener
self.addEventListener("fetch", (event) => {
var currentUrl = new URL(event.request.url);
if (currentUrl.origin === location.origin){
var newRequest = new Request(event.request, {
mode: "cors",
credentials: "same-origin",
headers: {
YOUR_CUSTOM_HEADER_NAME: YOUR_CUSTOM_HEADER_VALUE,
}
});
event.respondWith(fetch(newRequest));
}
else {
event.respondWith(fetch(event.request));
}
});
此外,如果您使用常量、变量来存储标头值和名称,浏览器会将变量的名称(小写)作为标头名称(而不是它的值)。
推荐阅读
- entity-framework - EF Core 3.0 1:0 与fluent的关系
- google-apps-script - 如何计算 ForEach 循环中具有唯一日期的行?
- php - 无法在 php 中创建对象并添加键/值对
- javascript - dts-gen 未创建名称空间问题
- kubernetes - 在 GKE for NGINX Ingress Controller 上自动创建 ClusterRoleBinding
- excel - 如何使带有超链接公式的单元格在粘贴后变为活动状态
- html - 如何使用 VBA 在网站中输入我的用户名
- python - 如何远程访问在 AWS EC2 上运行的 Python 烧瓶应用程序?
- gitlab - 使用 Gitlab API v4 从分支下载目录
- c# - 无法从程序集中加载任务工厂“CodeTaskFactory”,客户端未持有所需的权限