Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to How To Guides
How to Fetch API in JavaScript

How to Fetch API in JavaScript

How To Guides2,022 viewsBy Admin
how-tofetchjavascript

Advertisement

The Fetch API

The fetch() function is the modern, built-in way to make HTTP requests in JavaScript. It returns a Promise and works in every modern browser and in Node.js 18+.

Basic GET Request

async function getPosts() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const data = await res.json();
  console.log(data);
}
getPosts();

POST Request with JSON Body

async function createPost() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title: "Hello", body: "World", userId: 1 }),
  });
  const data = await res.json();
  return data;
}

Important: fetch Does NOT Reject on 404/500

This trips up beginners. A 404 or 500 still resolves — you must check res.ok yourself:

const res = await fetch(url);
if (!res.ok) {
  throw new Error(`Request failed: ${res.status}`);
}

Adding Headers & Auth Tokens

const res = await fetch("/api/profile", {
  headers: {
    "Authorization": `Bearer ${token}`,
    "Accept": "application/json",
  },
});

Handling Timeouts with AbortController

const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);

const res = await fetch(url, { signal: controller.signal });
clearTimeout(timeout);

FAQs

fetch vs axios — which should I use?

fetch is built-in and needs no install. axios adds conveniences (auto JSON parsing, interceptors, better error handling). For small projects, fetch is plenty.

Why is my fetch blocked by CORS?

CORS is enforced by the browser. The server must send Access-Control-Allow-Origin headers. You cannot fix CORS from the frontend alone. More in our how-to guides.

Advertisement