fetch
Sends an HTTP request and returns a promise of the response.
Available since: Web API
Syntax
fetch(url, options)Parameters
| Parameter | Type | Description |
|---|---|---|
| url | string | URL | The request URL. |
| options | object | Optional. method, headers, body, signal and other request settings. |
Return value
Promise<Response>A promise of a response with status, ok and the json() and text() methods.
Examples
A GET request and JSON parsing:
const response = await fetch('https://api.example.com/users/1');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const user = await response.json();
console.log(user.name);Output:
AnnaA POST request with JSON:
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Anna' }),
});
const created = await response.json();
console.log(created.id);Output:
7Notes
fetch() rejects only on network failure. 404 and 500 responses count as successful, so always check response.ok or response.status.
The fetch examples on this page do not run: they need a real server.
See also
- await — Waits for a promise and returns its value.
- JSON.parse — Parses a JSON string and returns the value.
- URLSearchParams — Reads and builds URL query parameters (the part after ?).
- Promise.prototype.catch — Handles a promise's error.
Related recipes
In the tutorial
- Server requests: fetch — The fetch function in JavaScript: GET and POST requests, the response object, status, response.ok, parsing JSON and handling errors.