Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Headers: set() method

BaselineWidely available

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.appendappends 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

js
set(name, value)

Parameters

name

The name of the HTTP header you want to set to a new value. If the given name is notthe name of an HTTP header, this method throws aTypeError.

value

The new value you want to set.

Return value

None (undefined).

Examples

Creating an emptyHeaders object is simple:

js
const myHeaders = new Headers(); // Currently empty

You could add a header to this usingHeaders.append, then set a newvalue for this header usingset():

js
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:

js
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①

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp