Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

fetch

Sends an HTTP request and returns a promise of the response.

Available since: Web API

Syntax

fetch(url, options)

Parameters

ParameterTypeDescription
urlstring | URLThe request URL.
optionsobjectOptional. 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:

Anna

A 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:

7

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.