Headers: Headers() コンストラクター
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.
構文
js
new Headers()
new Headers(init)
引数
例
簡単に空の Headers
オブジェクトを生成できます。
js
const myHeaders = new Headers(); // Currently empty
Headers.append
を使用してヘッダーを追加できます。
js
myHeaders.append("Content-Type", "image/jpeg");
myHeaders.get("Content-Type"); // 'image/jpeg' が返される
または、Headers
オブジェクトの生成時に必要なヘッダーを追加することもできます。次のスニペットでは、新しい Headers
を作成し、コンストラクターに初期化オブジェクトを引数として渡してヘッダーを追加しています。
js
const httpHeaders = {
"Content-Type": "image/jpeg",
"X-My-Custom-Header": "Zeke are cool",
};
const myHeaders = new Headers(httpHeaders);
最初の Headers
を初期化オブジェクトとして渡して、別の Headers
オブジェクトを生成できます。
js
const secondHeadersObj = new Headers(myHeaders);
secondHeadersObj.get("Content-Type"); // 'image/jpeg' が返される。最初のヘッダーオブジェクトから継承している
また、Headers
オブジェクトを作成する際に、二次元配列を使用して、同じ値を持つ複数のヘッダーを追加することができます。以下のスニペットでは、コンストラクターの引数に初期化配列を渡して、複数の Set-Cookie
ヘッダーを持つ新しい Headers
オブジェクトを作成しています。
js
const headers = [
["Set-Cookie", "greeting=hello"],
["Set-Cookie", "name=world"],
];
const myHeaders = new Headers(headers);
仕様書
Specification |
---|
Fetch # ref-for-dom-headers① |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Headers() constructor |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.