Headers.set()

这篇翻译不完整。请帮忙从英语翻译这篇文章

headers接口中 set() 方法在可以在已经声明中的headers对象修改已有的一组键值对或者创建一个新的键值对。

set() 方法和 append()方法不同的是声明的Headers对象是否已经存在对应的keys是否已经存在并且已经赋值。set() 方法将会覆盖之前的value,然而 append()方法只会在Headers对象的尾部添加一个新的键值对。

为了安全策略,一些 Headers对象中的键值对只能客户端去控制。这些key包括Forbidden response header name 和 Forbidden responese header names 。

语法

myHeaders.set(name, value);

参数

name
name就是需要对HTTP header 设置新值的key, 一般为字符串。如果设置的name 不是HTTP header规范里面规定的name,那么将会抛出错误"TypeError"。
value
 value 就是 name 对应的值。

返回

Void.

Example

创建一个新的 Headers 对象:

var myHeaders = new Headers(); // Currently empty

你可以用append()方法给Headers 对象增添一个新的键值对,然后用set()方法去改变这个键值对:

myHeaders.append('Content-Type', 'image/jpeg');
myHeaders.set('Content-Type', 'text/html');

如果这个键值对不存在,那么set()方法首先创建一个键值对,然后给它赋值。如果这个键值对存在,那么set()方法将会覆盖之前的value值:

myHeaders.set('Accept-Encoding', 'deflate');
myHeaders.set('Accept-Encoding', 'gzip');
myHeaders.get('Accept-Encoding'); // Returns 'gzip'

如果你需要增加一个键值对,而不是要覆盖之前的键值对,那么你需要用append()方法。

Specifications

Specification Status Comment
Fetch
set()
Living Standard  

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
set
Experimental
Chrome Full support 42
Full support 42
Full support 41
Disabled
Disabled From version 41: this feature is behind the Experimental Web Platform Features preference. To change preferences in Chrome, visit chrome://flags.
Edge Full support 14Firefox Full support 39
Full support 39
Full support 34
Disabled
Disabled From version 34: this feature is behind the dom.fetch.enabled preference. To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 29
Full support 29
Full support 28
Disabled
Disabled From version 28: this feature is behind the Experimental Web Platform Features preference.
Safari No support NoWebView Android Full support 42
Full support 42
Full support 41
Disabled
Disabled From version 41: this feature is behind the Experimental Web Platform Features preference.
Chrome Android Full support 42
Full support 42
Full support 41
Disabled
Disabled From version 41: this feature is behind the Experimental Web Platform Features preference. To change preferences in Chrome, visit chrome://flags.
Edge Mobile Full support YesFirefox Android No support NoOpera Android Full support 29
Full support 29
Full support 28
Disabled
Disabled From version 28: this feature is behind the Experimental Web Platform Features preference.
Safari iOS No support NoSamsung Internet Android Full support 4.0

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
User must explicitly enable this feature.
User must explicitly enable this feature.

See also

文档标签和贡献者

此页面的贡献者: astonesh
最后编辑者: astonesh,