Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make an HTTP request

Short answer

fetch() sends a request and returns a promise with the response. response.json() reads the body as JSON:

const response = await fetch('https://api.example.com/users/1');
const user = await response.json();
 
console.log(user.name);

Sending JSON

For a POST request, set the method, the Content-Type header and the body as a JSON string:

const response = await fetch('https://api.example.com/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Anna', email: 'anna@example.com' }),
});
const created = await response.json();

Headers

A token for an API is usually sent in the Authorization header:

const response = await fetch('https://api.example.com/orders', {
  headers: { Authorization: `Bearer ${token}` },
});

Common mistake

fetch() rejects only on network errors. A response with status 404 or 500 counts as successful, so check response.ok:

const response = await fetch('https://api.example.com/users/999');
 
if (!response.ok) {
  throw new Error(`Request failed with status ${response.status}`);
}

Functions used in this recipe

  • fetch — Sends an HTTP request and returns a promise of the response.
  • JSON.parse — Parses a JSON string and returns the value.

Thanks for reading!

Donate to the site — we work hard for you.