Skip to content
The App Code
How-to

Make a GET Request in JavaScript

Fetch JSON from an API in the browser or Node using the async fetch API.

Also known as: fetch GET, JavaScript fetch API

beginner

The fetch function returns a promise; await it, check response.ok, then await response.json() to get the parsed body.

What it is

fetch is the standard way to make HTTP requests in browsers and modern Node. It resolves to a Response object as soon as the headers arrive; reading the body is a second async step (response.json()), because the body streams in separately.

Crucially, fetch only rejects on network failure — an HTTP 404 or 500 still resolves successfully. You must check response.ok (true for 200–299) and throw yourself if you want error status codes to be treated as failures.

Worked example

async function getPost(id) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
  if (!res.ok) {
    throw new Error(`HTTP ${res.status}`);
  }
  return res.json();
}

getPost(1)
  .then((post) => console.log(post.title))
  .catch((err) => console.error(err));

Failure mode — when it misleads

The number-one gotcha: fetch does not reject on 4xx/5xx, so a try/catch alone won't catch a 500 — you must inspect response.ok. Reading the body twice (e.g. res.json() after res.text()) throws "body already read," because a response body can only be consumed once.

Sources & further reading