Request
Request represents an HTTP request: the URL, method, headers, body, and the signal used to cancel it, kept in one object. Passing it to fetch() sends the request.
You can send a request by passing a URL and options directly to fetch(). Use Request when you need to prepare a request first, then send it later or pass it to another function.
Request also has bodyUsed and four reading methods, which read the body given at construction. It has no body property.
Inheritance: Request doesn't inherit from other classes.
For how to send requests, see the guide Fetching data from the network.
Constructor
Creates a request from a URL and options. The parameters are the same as fetch().
Instance properties
All of these properties are readable and not writable.
| Property | Description |
|---|---|
url read-only | The request URL, a full URL after normalization |
method read-only | The request method, uppercase |
headers read-only | The request headers |
signal read-only | The AbortSignal used to cancel this request |
bodyUsed read-only | Whether the body has already been read |
Instance methods
| Method | Description |
|---|---|
clone() | Returns an independent copy |
The four methods that read the body follow the same rules as on Response: they all return a Promise, and once any one has been read, none of the others can be read.
| Method | Description |
|---|---|
json() | Parses the body as JSON |
text() | Decodes the body as UTF-8 |
arrayBuffer() | Gets the body as an ArrayBuffer |
blob() | Gets the body as a Blob |
Examples
async function main() {
const req = new Request('https://httpbin.org/post', { method: 'POST', body: 'hello' });
const res = await fetch(req);
const echo = await res.json();
console.log(echo.data);
}
main();Result: Prints hello. The request is sent with the method and body from the Request.
Differences from the web
- There's no
bodyproperty. The body can only be read with the four reading methods. - There are no properties such as
mode,credentials,cache, orredirect. signalis the very object given at construction. On the web it's a separately created signal that follows it.- All method names are converted to uppercase. The web converts only standard method names such as
GETandPOSTto uppercase, and keeps'patch'as is. From the code; not verified in the simulator.
See also
fetch(): sends the requestResponse: the response to the requestAbortController: canceling a request