fetch()
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
// Basic GET request
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
| Argument | Description |
|---|---|
| URL | Specifies the request URL as a string. |
| options | Optional. Specifies request settings as an object. You can set properties such as method, headers, and body. |
Response Object Properties and Methods
| Property / Method | Description |
|---|---|
| response.ok | Returns true if the HTTP status code is between 200 and 299. |
| response.status | Returns 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
// Fetching JSON data with a GET request
fetch("https://api.example.com/users")
.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);
});
// Sending data with a POST request
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "Taro", 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);
});
// Using async/await
async function getUsers() {
try {
var response = await fetch("https://api.example.com/users");
var data = await response.json();
console.log(data);
} catch (error) {
console.log("Network error: " + error.message);
}
}
getUsers();
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
41 or earlier ×
38 or earlier ×
Android Browser
47+ ○
41 or earlier ×
Chrome Android
47+ ○
41 or earlier ×
Firefox Android
79+ ○
38 or earlier ×If you find any errors or copyright issues, please contact us.