如何在 Javascript 中删除 HTTP 特定标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2464192/
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-08-23 00:29:03  来源:igfitidea点击:

How to remove HTTP specific headers in Javascript

javascriptajaxhttp-headersxmlhttprequest

提问by Andres

Is it possible to, before sending a http message, remove some specific http headers using javascript / XmlHttpRequest ?

是否可以在发送 http 消息之前使用 javascript / XmlHttpRequest 删除一些特定的 http 标头?

I'm using a proprietary browser, so there's no way to do it using browser specific solution.

我使用的是专有浏览器,因此无法使用特定于浏览器的解决方案来实现。

For example, I want to remove the header 'Authorization' before send the message

例如,我想在发送消息之前删除标题“授权”

POST /social/rpc?oauth_version=1.0& ... HTTP/1.1

Accept: text/html, image/png, image/*, */*
Accept-Language: ko
Authorization: Basic Og==
Host: test.myhost.com

Regards

问候

采纳答案by Adam

You could use the setRequestHeader method of the XmlHttpRequest object assuming your browser supports it, It is part of the W3C spec. It is also implemented by IE.

假设您的浏览器支持它,您可以使用 XmlHttpRequest 对象的 setRequestHeader 方法,它是W3C 规范的一部分。它也是由 IE 实现的

var req = new XMLHttpRequest();
req.setRequestHeader("Authorization", "");

回答by Fancyoung

When I use jquery-file-upload, and want to remove the header in the optionsmethod, setting it to nullor ''doesn't work for me. I use this instead:

当我使用 jquery-file-upload 并想删除options方法中的标题时,将其设置为null''不适合我。我用这个代替:

req.setRequestHeader("Authorization");

req.setRequestHeader("Authorization");

回答by BalusC

Never done it, but in theory you could try:

从来没有做过,但理论上你可以尝试:

xhr.setRequestHeader('Authorization', null);

There's also an unspecified removeRequestHeader()function in some implementations, you may want to give it a try as well.

removeRequestHeader()在某些实现中还有一个未指定的函数,您可能也想尝试一下。

回答by Dmitry Efimenko

Adam's answer didn't work for me. However, the following did:

亚当的回答对我不起作用。但是,以下做了:

xhr.setRequestHeader('Authorization', ' ');

notice, second parameter is a string containing a space instead of empty space. It does not remove header completely, but sets it to the empty string, which might be enough for some cases.

注意,第二个参数是一个包含空格而不是空格的字符串。它不会完全删除标头,而是将其设置为空字符串,这对于某些情况可能就足够了。