最終更新日: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.
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. |
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. |
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. |
headers.entries(): IterableIterator<[string, string]>;
Returns an iterator containing all header field key-value pairs.
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.
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.
headers.getSetCookie(): Array<string>;
Returns an array containing the values of all Set-Cookie
header fields.
headers.has(name: string): boolean;
Checks if the Headers
object contains the specified header field.
headers.keys(): IterableIterator<string>;
Returns an iterator containing the names of all header fields.
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.
headers.values(): IterableIterator<string>;
Returns an iterator containing the values of all header fields.
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));
});