Headers: set() method
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.
Note: This feature is available inWeb Workers.
Theset()
method of theHeaders
interfacesets a new value for an existing header inside aHeaders
object, or addsthe header if it does not already exist.
The difference betweenset()
andHeaders.append
is that ifthe specified header already exists and accepts multiple values,set()
overwrites the existing value with the new one, whereasHeaders.append
appends the new value to the end of the set of values.
For security reasons, some headers can only be controlled by the user agent. Theseheaders include theforbidden request headersandforbidden response header names.
Syntax
set(name, value)
Parameters
Return value
None (undefined
).
Examples
Creating an emptyHeaders
object is simple:
const myHeaders = new Headers(); // Currently empty
You could add a header to this usingHeaders.append
, then set a newvalue for this header usingset()
:
myHeaders.append("Content-Type", "image/jpeg");myHeaders.set("Content-Type", "text/html");
If the specified header does not already exist,set()
will create it andset its value to the specified value. If the specified header does already exist anddoes accept multiple values,set()
will overwrite the existing value withthe new one:
myHeaders.set("Accept-Encoding", "deflate");myHeaders.set("Accept-Encoding", "gzip");myHeaders.get("Accept-Encoding"); // Returns 'gzip'
You'd needHeaders.append
to append the new value onto the values, notoverwrite it.
Specifications
Specification |
---|
Fetch # ref-for-dom-headers-set① |