agyanadda@gmail.com

JS Fetch API

Asynchronous JavaScript 1 min read Updated Dec 1, 2026 Topic 33 of 38

fetch() loads data from a server without reloading the page.

GET data

const res = await fetch('https://api.example.com/users');
if (!res.ok) throw new Error('HTTP ' + res.status);
const users = await res.json();

Steps

  1. fetch(url) returns a Promise of a Response
  2. Check res.ok (status 200–299)
  3. Read the body with res.json() or res.text()

POST data

await fetch('/api/contact', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Asha' })
});

fetch only rejects on network failure — a 404 or 500 still "succeeds", so always check res.ok.

Example

Example — Load users from an API HTML
<button id="load">Load users</button>
<ul id="users"></ul>
<p id="msg"></p>

<script>
  document.getElementById('load').onclick = async () => {
    const msg = document.getElementById('msg');
    const list = document.getElementById('users');
    msg.textContent = 'Loading...';
    list.innerHTML = '';
    try {
      const res = await fetch('https://jsonplaceholder.typicode.com/users');
      if (!res.ok) throw new Error('HTTP ' + res.status);
      const users = await res.json();
      for (const u of users) {
        const li = document.createElement('li');
        li.textContent = `${u.name} – ${u.address.city}`;
        list.append(li);
      }
      msg.textContent = users.length + ' users loaded.';
    } catch (err) {
      msg.textContent = 'Could not load data: ' + err.message;
    }
  };
</script>

Uses the free JSONPlaceholder test API.

Try it Now »

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method reads a JSON response body?

Exercise 2 True / False

fetch() rejects the Promise when the server returns 404.

Exercise 3 Fill in the Blank

To send data, set method: '___' in the fetch options.

Frequently Asked Questions

The browser blocks requests to another domain unless that server allows it. The fix is on the server (CORS headers), not in your fetch code.