--- title: Headers.get() slug: Web/API/Headers/get tags: - get() translation_of: Web/API/Headers/get ---

{{APIRef("Fetch")}}{{ SeeCompatTable() }}

get() 方法以 {{domxref("ByteString")}} 形式从Headers对象中返回指定header的全部值. 如果Header对象中不存在请求的header,则返回 null.

Note:出于安全原因, 部分头信息只能被用户代理控制. 这些头信息包括 {{Glossary("Forbidden_header_name", "forbidden header names", 1)}}  和 {{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.

Syntax

myHeaders.get(name);

Parameters

name
从Headers对象中检索的HTTP header 名,如果HTTP header中不存在指定header名则会抛出一个{{jsxref("TypeError")}}.

Returns

以 {{domxref("ByteString")}} 形式返回检索到的值.

Example

创建一个空的Headers对象:

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

可以通过get()方法来获取header中的值:

myHeaders.append('Content-Type', 'image/jpeg');
myHeaders.get('Content-Type'); // Returns 'image/jpeg'

如果存在多个header值,那么只有第一个值会被返回:

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

Note: {{domxref("Headers.getAll")}} used to have this functionality, with {{domxref("Headers.get")}} returning only the first value added to the Headers object. The latest spec has removed getAll(), and updated get() to return all values.

Specifications

Specification Status Comment
{{SpecName('Fetch','#dom-headers-get','get()')}} {{Spec2('Fetch')}}

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support {{ CompatChrome(42) }}
{{ CompatChrome(41) }} behind pref
 
{{ CompatGeckoDesktop(39)}}
34 behind pref
{{ CompatNo }}

29
28 behind pref

{{ CompatNo }}
Feature Android Firefox Mobile (Gecko) Firefox OS (Gecko) IE Phone Opera Mobile Safari Mobile Chrome for Android
Basic support {{ CompatNo }} {{ CompatNo }} {{ CompatNo }} {{ CompatNo }} {{ CompatNo }} {{ CompatNo }} {{ CompatNo }}

See also