The Headers()
constructor creates a new Headers
object.
Headers()
Syntax
new Headers(init);
Parameters
-
init
Optional -
An object containing any HTTP headers that you want to pre-populate your
Headers
object with. This can be a simple object literal withString
values, an array of name-value pairs, where each pair is a 2-element string array; or an existingHeaders
object. In the last case, the newHeaders
object copies its data from the existingHeaders
object.
Examples
Creating an empty Headers
object is simple:
var myHeaders = new Headers(); // Currently empty
You could add a header to this using Headers.append
:
myHeaders.append('Content-Type', 'image/jpeg'); myHeaders.get('Content-Type'); // Returns 'image/jpeg'
Or you can add the headers you want as the Headers
object is created. In the following snippet we create a new Headers
object, adding some headers by passing the constructor an init object as an argument:
var httpHeaders = { 'Content-Type' : 'image/jpeg', 'X-My-Custom-Header' : 'Zeke are cool' }; var myHeaders = new Headers(httpHeaders);
You can now create another Headers
object, passing it the first Headers
object as its init object:
var secondHeadersObj = new Headers(myHeaders); secondHeadersObj.get('Content-Type'); // Would return 'image/jpeg' — it inherits it from the first headers object
You can also add the headers you want as the Headers
object is created by using a two-dimensional array to add multiple headers with the same values. In the following snippet we create a new Headers
object with multiple Set-Cookie
headers by passing the constructor an init array as an argument:
var headers = [ ['Set-Cookie', 'greeting=hello'], ['Set-Cookie', 'name=world'] ]; var myHeaders = new Headers(headers);
Specifications
Specification |
---|
Fetch Standard # ref-for-dom-headers① |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
Headers |
42
|
14
|
39
|
No
|
29
|
10.1
|
42
|
42
|
44
|
29
|
10.3
|
4.0
|
See also
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers