Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

The Fetch API: Making HTTP Requests in JavaScript

5 min read Updated By the SkillNewton team

What is the Fetch API?

The Fetch API is the browser's built-in, promise-based interface for making HTTP requests from JavaScript. You call fetch(url, options), which returns a promise for a Response object, and then read the body as JSON, text or another format. It replaced XMLHttpRequest for most work and is also available in Node.js.

Request, Response and Headers: the core objects

Fetch is built from a few objects. A Request describes what to send: URL, method, headers and body. A Response describes what came back: status code, headers and a body you can read once. Headers is a case-insensitive map of HTTP headers.

Response memberMeaning
statusHTTP status code, such as 200, 404 or 500
oktrue when the status is in the range 200 to 299
headers.get(name)Reads a response header, such as Content-Type
json(), text(), blob()Read the body; each returns a promise and can be used once

If HTTP methods and status codes are new to you, read our guide to REST APIs first.

Making a GET request and checking response.ok

The most important rule of fetch: the promise only rejects on a network failure, such as no connection, a DNS error or a blocked CORS request. A 404 or 500 response still resolves normally. You must check response.ok yourself.

async function getJSON(url) {
  const response = await fetch(url, { headers: { Accept: 'application/json' } });
  if (!response.ok) {
    throw new Error(`Request failed: ${response.status} ${response.statusText}`);
  }
  return response.json();
}

try {
  const courses = await getJSON('/api/courses?level=beginner');
  console.log(courses.length);
} catch (error) {
  console.error(error.message);   // network failure, HTTP error or invalid JSON
}

Build query strings with URLSearchParams rather than joining strings by hand, so values are encoded correctly: new URLSearchParams({ q: 'php & mysql' }) produces q=php+%26+mysql.

Sending data: POST with JSON or form data

To send JSON, set the method, a Content-Type header and a body produced by JSON.stringify(). To send a form, pass a FormData object and let the browser set the multipart header, including its boundary.

// JSON body
const response = await fetch('/api/enquiries', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
  body: JSON.stringify({ name: 'Meera', course: 'php-foundation-course' }),
});

// Form body (works with $_POST and $_FILES in PHP)
const form = document.querySelector('#upload');
await fetch(form.action, { method: 'POST', body: new FormData(form) });

Other methods work the same way: pass method: 'PUT', 'PATCH' or 'DELETE' with a body where needed. A successful DELETE often returns status 204 with no body, so check the status before calling response.json(), which would fail on an empty response.

Requests to the same origin send cookies by default (credentials: 'same-origin'). Use credentials: 'include' only when a cross-origin API is designed to accept cookies. The JSON guide explains how the body is encoded and decoded on both sides.

Timeouts and cancelling with AbortController

Fetch has no timeout option of its own. Pass an AbortSignal, and the request is cancelled when the signal aborts; the promise then rejects with an error named AbortError, or TimeoutError for AbortSignal.timeout().

// Give up after 8 seconds
const res = await fetch('/api/report', { signal: AbortSignal.timeout(8000) });

// Cancel an older search when the user types again
let controller;
searchInput.addEventListener('input', async () => {
  controller?.abort();
  controller = new AbortController();
  try {
    const res = await fetch(`/api/search?q=${encodeURIComponent(searchInput.value)}`,
                            { signal: controller.signal });
    if (!res.ok) throw new Error(res.status);
    showResults(await res.json());
  } catch (err) {
    if (err.name !== 'AbortError') showError(err);
  }
});

CORS basics: why some requests are blocked

Browsers apply the same-origin policy: a page can freely read responses only from its own origin, meaning the same scheme, host and port. Cross-Origin Resource Sharing (CORS) lets a server opt in to being read by other origins through response headers.

  • The server sends Access-Control-Allow-Origin with the allowed origin, or * for public data without cookies.
  • Requests with methods such as PUT or DELETE, custom headers, or a JSON Content-Type trigger a preflight: an automatic OPTIONS request the server must answer with Access-Control-Allow-Methods and Access-Control-Allow-Headers.
  • Cookies across origins also need Access-Control-Allow-Credentials: true and a specific origin, never *.
  • Setting mode: 'no-cors' does not fix an error; it gives you an opaque response you cannot read.

CORS is enforced by the browser to protect users, not your server. It is fixed on the server that owns the API, or by calling that API from your own back end. See our web security guide for how it fits with other protections.

Calling an API with fetch, step by step

  1. Confirm the endpoint, method, required headers and response format in the API documentation.
  2. Write a small helper that calls fetch, checks response.ok and parses JSON.
  3. Add an AbortSignal timeout to every request.
  4. Wrap calls in try/catch and show the user a clear message on failure.
  5. Open the Network panel in dev tools to inspect the request headers, payload, status and response.
  6. Never put secret API keys in browser code; call such APIs from your server instead.

Create a cities.php endpoint that returns a JSON array of Indian cities filtered by a q parameter, and a page with a search input.

  1. On each input event, fetch cities.php?q=... and list the results using textContent.
  2. Abort the previous request whenever a new one starts.
  3. Make the endpoint return status 400 for an empty query and show a helpful message when response.ok is false.
  4. Add an eight-second timeout and test it by adding sleep(10) to the PHP file.

You are done when fast typing never shows stale results and every failure produces a readable message instead of a console error. The AJAX guide extends this into full form submissions, and SkillNewton's advanced PHP course builds API-driven projects on the same foundations.

Common mistakes

  • Assuming fetch rejects on a 404 or 500 and never checking response.ok.
  • Forgetting JSON.stringify() and sending [object Object] as the body.
  • Setting Content-Type manually for FormData, which removes the multipart boundary.
  • Reading the body twice, for example calling text() after json().
  • Using mode: 'no-cors' to silence a CORS error and then getting an empty response.
  • Embedding private API keys in front-end JavaScript where anyone can read them.

Frequently asked questions

Is fetch better than XMLHttpRequest or axios?

Fetch is built in, promise-based and covers most needs. XMLHttpRequest still offers upload progress events, and libraries such as axios add conveniences like automatic JSON handling, but neither is required for typical requests.

Why does my fetch work in Postman but not in the browser?

Postman is not a browser and does not enforce CORS. If the API does not send the right Access-Control-Allow-* headers, the browser blocks your page from reading the response.

How do I send a file with fetch?

Append the file input to a FormData object and send it as the body with POST. On the server, validate it carefully as described in our PHP file uploads guide.

Can I use fetch in Node.js?

Yes. Current Node.js versions include a global fetch. CORS does not apply there because it is a browser protection.

Want to Learn This Properly?

The Advanced PHP Web Development & Full-Stack Application Development (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.