The Fetch API: Making HTTP Requests in JavaScript
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 member | Meaning |
|---|---|
status | HTTP status code, such as 200, 404 or 500 |
ok | true 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-Originwith the allowed origin, or*for public data without cookies. - Requests with methods such as
PUTorDELETE, custom headers, or a JSONContent-Typetrigger a preflight: an automaticOPTIONSrequest the server must answer withAccess-Control-Allow-MethodsandAccess-Control-Allow-Headers. - Cookies across origins also need
Access-Control-Allow-Credentials: trueand 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
- Confirm the endpoint, method, required headers and response format in the API documentation.
- Write a small helper that calls
fetch, checksresponse.okand parses JSON. - Add an
AbortSignaltimeout to every request. - Wrap calls in
try/catchand show the user a clear message on failure. - Open the Network panel in dev tools to inspect the request headers, payload, status and response.
- Never put secret API keys in browser code; call such APIs from your server instead.
Practical exercise: a city search box
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.
- On each
inputevent, fetchcities.php?q=...and list the results usingtextContent. - Abort the previous request whenever a new one starts.
- Make the endpoint return status 400 for an empty query and show a helpful message when
response.okis false. - 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-Typemanually forFormData, which removes the multipart boundary. - Reading the body twice, for example calling
text()afterjson(). - 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.