Headers

最終更新日:2024-08-14 19:50:31

The Headers object provides a set of interfaces for manipulating HTTP request and response headers. Its design is based on the Headers interface of the Web API standard.

Constructor

const headers = new Headers(init?);

Parameters:

Parameter Name Type Required Description
init object | Array<[string, string]> | Headers No Initializes the Headers object. You can pass in an object, an array containing key-value pairs, or another Headers object for initialization.

Methods

append

headers.append(name: string, value: string): void;

Appends a new value to the specified header field. If the header field does not exist, it is added directly.

Parameters:

Attribute Name Type Required Description
name string Yes Header field name.
value string Yes The new value to append.

delete

headers.delete(name: string): void;

Deletes the specified header field from the Headers object.

Parameters:

Attribute Name Type Required Description
name string Yes Header field name.

entries

headers.entries(): IterableIterator<[string, string]>;

Returns an iterator containing all header field key-value pairs.

forEach

headers.forEach(callback: (value: string, name: string, headers: Headers) => void, thisArg?: any): void;

Iterates over all header fields in the Headers object.

Parameters:

  • callback: The function to be called for each header field, accepting three arguments:

    • value: The value of the header field.
    • name: The name of the header field.
    • headers: The Headers object itself.
  • thisArg (optional): The value to use as this when executing the callback function.

get

headers.get(name: string): string \| null;

Retrieves the value of the specified header field from the Headers object. Returns null if the header field does not exist.

getSetCookie

headers.getSetCookie(): Array<string>;

Returns an array containing the values of all Set-Cookie header fields.

has

headers.has(name: string): boolean;

Checks if the Headers object contains the specified header field.

keys

headers.keys(): IterableIterator<string>;

Returns an iterator containing the names of all header fields.

set

headers.set(name: string, value: string): void;

Sets the value of the specified header field. If the header field does not exist, a new key-value pair is added.

values

headers.values(): IterableIterator<string>;

Returns an iterator containing the values of all header fields.

Code Example

function handleEvent(event) {
  // Create a Headers object
  const headers = new Headers({
    'my-header-x': 'hello world',
  });

  // Create a Response object and set Headers
  const response =  new Response('hello world', {
    headers,
  });

  return response;
}

addEventListener('fetch', (event) => {
  event.respondWith(handleEvent(event));
});

References