Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

JavaScript Dictionary

  1. Home
  2. JavaScript Dictionary
  3. fetch()

fetch()

Since: Web API(2015)

A function that sends an HTTP request to a server and retrieves the response. It returns a Promise, so it is handled as an asynchronous operation.

Syntax

fetch("URL")
	.then(function(response) { return response.json(); })
	.then(function(data) { /* Process the retrieved data */ });

// Using async/await
var response = await fetch("URL");
var data = await response.json();

Arguments

ArgumentDescription
URLSpecifies the request URL as a string.
optionsOptional. Specifies request settings as an object. You can set properties such as method, headers, and body.

Response Object Properties and Methods

Property / MethodDescription
response.okReturns true if the HTTP status code is between 200 and 299.
response.statusReturns the HTTP status code as a number. 200 means success, 404 means not found, and 500 means a server error.
response.json()Parses the response as JSON and returns it as a JavaScript object.
response.text()Returns the response as a plain text string.

Sample Code

fetch("https://wp-p.info/sandbox/api.php")
	.then(function(response) {
		if (!response.ok) {
			throw new Error("HTTP error: " + response.status); // Throws an exception on error
		}
		return response.json(); // Parses the response as JSON
	})
	.then(function(data) {
		console.log(data); // Logs the retrieved data
	})
	.catch(function(error) {
		console.log("Network error: " + error.message);
	});

The following example shows how this works in practice:

fetch("https://wp-p.info/sandbox/api.php", {
	method: "POST",
	headers: {
		"Content-Type": "application/json"
	},
	body: JSON.stringify({ name: "user_a", age: 25 }) // Converts the object to a JSON string before sending
})
	.then(function(response) { return response.json(); })
	.then(function(data) {
		console.log("Registered: " + data.id);
	});

async/await is covered in detail on a separate page. See async / await for more.

async function getUsers() {
	try {
		var response = await fetch("https://wp-p.info/sandbox/api.php");
		var data = await response.json();
		console.log(data);
	} catch (error) {
		console.log("Network error: " + error.message);
	}
}
getUsers();

Common Mistakes

Mistake 1: Missing HTTP error handling

fetch() does not reject the Promise on HTTP errors like 404 or 500. Without checking response.ok, error responses silently pass through to the next .then() and are treated as normal data.

// NG: Without checking response.ok, 404/500 errors silently pass through
fetch("https://wp-p.info/sandbox/api.php?format=invalid")
	.then(function(response) {
		return response.json(); // You reach this even on a 404
	})
	.then(function(data) {
		console.log(data); // Processing continues despite the error
	});

The corrected version looks like this:

// OK: Always check response.ok before processing the data
fetch("https://wp-p.info/sandbox/api.php?format=invalid")
	.then(function(response) {
		if (!response.ok) {
			throw new Error("HTTP error: " + response.status);
		}
		return response.json();
	})
	.then(function(data) {
		console.log(data);
	})
	.catch(function(error) {
		console.log("Error: " + error.message);
	});

Mistake 2: Calling response.json() twice

The response body can only be read once. Calling response.json() a second time raises TypeError: Already read because the stream has already been consumed.

// NG: response.json() can only be called once
fetch("https://wp-p.info/sandbox/api.php")
	.then(function(response) {
		console.log(response.json()); // 1st call
		return response.json(); // 2nd call: throws an error
	});

Practical Patterns

<button id="fetch-btn">Fetch Data</button>
<pre id="result"></pre>

This produces the following output:

var fetchBtn = document.getElementById("fetch-btn");
var resultEl = document.getElementById("result");

if (fetchBtn && resultEl) {
	fetchBtn.addEventListener("click", function() {
		resultEl.textContent = "Loading...";
		fetchBtn.disabled = true;

		fetch("https://wp-p.info/sandbox/api.php?format=json")
			.then(function(response) {
				if (!response.ok) {
					throw new Error("HTTP error: " + response.status);
				}
				return response.json();
			})
			.then(function(data) {
				resultEl.textContent = JSON.stringify(data, null, 2);
			})
			.catch(function(error) {
				resultEl.textContent = "Error: " + error.message;
			})
			.finally(function() {
				fetchBtn.disabled = false;
			});
	});
}

// Pattern 2: Authenticated request with an API token
function fetchWithAuth(url, token) {
	return fetch(url, {
		headers: {
			"Authorization": "Bearer " + token,
			"Content-Type": "application/json"
		}
	}).then(function(response) {
		if (!response.ok) { throw new Error("HTTP error: " + response.status); }
		return response.json();
	});
}

// Pattern 3: Timeout handling with AbortController
function fetchWithTimeout(url, ms) {
	var controller = new AbortController();
	var timeoutId = setTimeout(function() { controller.abort(); }, ms);
	return fetch(url, { signal: controller.signal })
		.then(function(response) {
			clearTimeout(timeoutId);
			if (!response.ok) { throw new Error("HTTP error: " + response.status); }
			return response.json();
		})
		.catch(function(error) {
			if (error.name === "AbortError") {
				throw new Error("Request timed out (" + ms + "ms)");
			}
			throw error;
		});
}

View sample page (Pattern 1 demo)

Overview

fetch() is a function for making HTTP requests to a server. It works as a Promise-based asynchronous operation and is used to retrieve data from an API or send form data to a server.

fetch() only rejects the Promise on network errors — it does not reject for HTTP errors such as 404 or 500. Because of this, you need to check response.ok or response.status to handle HTTP errors explicitly.

fetch() was designed as a modern replacement for the older XMLHttpRequest. Its Promise-based design makes code easier to read, and combining it with async/await allows you to write asynchronous code in an intuitive, synchronous style.

Browser Compatibility

Chrome Chrome
49+
41 or earlier ×
Firefox Firefox
57+
38 or earlier ×
Safari Safari
18+
10 or earlier ×
Edge Edge
80+
13 or earlier ×
IE IE
11 ×
Not supported in any version
Opera Opera
48+
28 or earlier ×
iOS Safari iOS Safari
18+
10 or earlier ×
Android Browser Android Browser
47+
41 or earlier ×
Chrome Android Chrome Android
47+
41 or earlier ×
Firefox Android Firefox Android
79+
38 or earlier ×

If you find any errors or copyright issues, please .