Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 55 of 58

Fetching data with fetch

Request data from a web API with fetch, read JSON responses, check response.ok, send POST requests, handle network errors and understand why CORS can block you.

15 minAsynchronous JavaScriptUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonFetch JSON from an API with async and await, check for HTTP errors, send data with POST and show loading and error states.

After this lesson you can load live data from the internet into your page. You will write a small fetch request, turn the reply into JavaScript data, deal with failure, and send data back.

You need async and await and, ideally, JSON. Everything in this lesson builds on them.

What fetch does

fetch(url) asks a server for something and returns a promise. When the server begins answering, the promise fulfils with a Response object. That object holds the status, the headers and the body. Reading the body is a second asynchronous step, because the data may still be arriving.

javascript
async function getTodo(id) {
  const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.status}`);
  }
  return response.json();
}

const item = await getTodo(1);
console.log(item.title, item.completed); // delectus aut autem false

The example uses a free practice API called JSONPlaceholder, which serves made-up data for learning. Its data could change one day, so do not rely on the exact text. The top-level await works in a module or in the browser console; in a normal script, wrap it in an async function.

Step by step:

  1. fetch(...) sends a GET request, the default, and await waits for the response headers.
  2. response.ok is true for status codes 200 to 299.
  3. response.json() reads the body and parses it as JSON. It also returns a promise, so we return it (an async function waits for it) or await it.

Other readers exist for other data: response.text() for plain text or HTML, and response.blob() for files such as images.

Try it

Press Try it, then run the code. It fetches a to-do item and shows the fields. The preview is an isolated frame, but this API allows requests from it.

html
<p id="status">Loading...</p>
<pre id="out"></pre>
<script>
  const statusLine = document.getElementById("status");
  const out = document.getElementById("out");

  async function getTodo(id) {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos/" + id);
    if (!response.ok) throw new Error("Request failed with status " + response.status);
    return response.json();
  }

  async function show(id) {
    try {
      const item = await getTodo(id);
      statusLine.textContent = "Loaded";
      out.textContent = "title: " + item.title + "\ncompleted: " + item.completed;
    } catch (error) {
      statusLine.textContent = "Something went wrong: " + error.message;
    }
  }

  show(1);
</script>

You should see Loaded, then title: delectus aut autem and completed: false. Change show(1) to show(99999). That item does not exist, the server answers 404, and the page shows Something went wrong: Request failed with status 404. Switch your device offline and the message will be about a failed network request instead.

Two kinds of failure

This is the most important thing to remember about fetch:

  • A network failure (no connection, a bad domain, blocked by CORS) rejects the promise with a TypeError. The message depends on the browser, for example "Failed to fetch" in Chrome.
  • An HTTP error status (404, 500 and so on) is not a failure as far as fetch is concerned. The promise fulfils normally, and response.ok is false.

So always check response.ok or response.status, as the examples do, and wrap the whole thing in try/catch. Forgetting this leads to the confusing situation where your await response.json() fails on an error page, long after the real problem.

Sending data with POST

Pass a second argument, an options object, to change the method and add a body.

javascript
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json; charset=UTF-8" },
  body: JSON.stringify({ title: "hello", body: "world", userId: 1 }),
});
console.log(response.status);        // 201
console.log(await response.json());  // { title: 'hello', body: 'world', userId: 1, id: 101 }

The body must be a string, so use JSON.stringify. The Content-Type header tells the server it is JSON. This practice API pretends to save your post and answers with status 201 ("created") and an id, but nothing is really stored.

Building a query string

Parameters after a ? in the URL are the query string. URLSearchParams builds one and handles special characters for you:

javascript
const params = new URLSearchParams({ userId: 1, _limit: 2 });
console.log(String(params)); // userId=1&_limit=2
const response = await fetch("https://jsonplaceholder.typicode.com/todos?" + params);
const todos = await response.json();
console.log(todos.length);   // 2

Several requests at once

Independent requests should run together:

javascript
const [a, b] = await Promise.all(
  [1, 2].map(id =>
    fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then(r => r.json())
  )
);
console.log(a.id, b.id); // 1 2

Loading, success and error states

Real pages should show the user what is happening. A request has three phases, and each deserves a message: loading ("Loading..."), success (the data) and error (a calm explanation and a way to retry). The try-it example above does that with its status line. Also disable the submit button while a POST is in flight, so a double click does not send it twice.

You can cancel a request with an AbortController. Pass { signal: controller.signal } to fetch, and call controller.abort(). The pending promise then rejects with an error whose name is AbortError. That is useful when a user types a new search before the old one finished.

CORS in plain words

Browsers protect users with the same-origin policy: a page on one site is not allowed to read responses from another site unless that site agrees. The agreement is a response header, Access-Control-Allow-Origin. If it is missing, your fetch fails with a network error and the console mentions CORS, even though the server did answer.

You cannot fix this from the front end. Either the API's owner has to allow your origin, or you call it through your own server. It is the server's job, not something to work around with a library. Public practice APIs generally allow all origins. A request to your own site or localhost is same-origin and not affected.

Secrets belong on a server. Never put an API key that must stay private in front-end JavaScript, because anyone can open the Network panel (see Debugging with the browser tools) and read it.

Common mistakes

  • Not checking response.ok. A 404 or 500 page then flows into your code as if it were data.
  • Forgetting to await response.json(). You get a promise, not the data.
  • Forgetting JSON.stringify for POST. Sending an object directly gives the text [object Object].
  • Missing the Content-Type header. The server may not understand the body.
  • Reading the body twice. A response body can be read only once. Call response.clone() first if you really need two reads.
  • Treating CORS as a bug in your code. It is a server setting; check the Network panel for the real status and headers.
  • No loading or error message. To the user, a silent page looks broken.
  • Hard-coding secrets in front-end code. Anyone can read them.

You can paste a response into the JSON formatter to make it easier to read while you work out its shape.

Exercise

Write async function loadTodos(limit) that fetches https://jsonplaceholder.typicode.com/todos?_limit= followed by the limit, checks response.ok, and returns the array. Use it to put each title into a list on the page, with "Loading..." shown first and an error message in a catch. Then change the URL to a non-existent path such as /todoz to confirm your error message appears.

Next, the final section: organise code into files with Modules: import and export.

Key points

  • fetch(url) returns a promise for a Response, and response.json() returns another promise for the parsed data.
  • fetch only rejects on network failure; a 404 or 500 still resolves, so check response.ok yourself.
  • To send data, pass method, headers and a JSON.stringify body in the options object.
  • A good request has three states to show the user: loading, success and error.
  • Browsers block cross-origin responses unless the server allows them with CORS headers, and that cannot be fixed from your page.

Check yourself

1. A server answers with status 404. What does fetch do?
2. How do you read a JSON body from a response?
3. Which options send an object as JSON in a POST request?
4. What is CORS?

Free tools for this lesson