JavaScript Fetch API
The Fetch API interface allows web browser to make HTTP requests to a web server.
😀 No need for XMLHttpRequest anymore.
It can be used to load text files, images, and many other types of resources.
Fetching a Text File
The simplest use of fetch() is to download a text file.
Example
Code:
// Async function to download a file
async function loadText(file) {
const response = await fetch(file);
myDisplayer(await response.text());
}
// Call the async function
loadText("demo.txt");
Try it Yourself »
The Response Object
JavaScript can continue running while waiting for the server to respond.
The fetch() method returns a Promise that resolves to a Response object.
Example
The result is a Response object.
// Async function to download a file
async function loadText(file) {
const response = await fetch(file);
myDisplayer(response);
}
Try it Yourself »
The Response object contains information about the server response.
| Property / Method | Description |
|---|---|
ok |
True if the request succeeded. |
status |
The HTTP status code. |
statusText |
The HTTP status message. |
text() |
Reads the response as text. |
json() |
Reads the response as JSON. |
blob() |
Reads the response as binary data. |
bytes() |
Reads the response as bytes. |
arrayBuffer() |
Reads the response as an ArrayBuffer |
The ok Property
Example
The response.ok should be true.
// Async function to download a file
async function loadText(file) {
const response = await fetch(file);
myDisplayer(response.ok);
}
Try it Yourself »
The status Property
Example
The response.status should be 200.
// Async function to download a file
async function loadText(file) {
const response = await fetch(file);
myDisplayer(response.status);
}
Try it Yourself »
The url Property
Example
// Async function to download a file
async function loadText(file) {
const response = await fetch(file);
myDisplayer(response.url);
}
Try it Yourself »
Fetching JSON
The json() method converts a JSON response into a JavaScript object.
Example
async function loadCustomer() {
const response = await fetch("customer.json");
const customer = await response.json();
myDisplayer(customer.name);
}
// Call the async function
loadCustomer();
Try it Yourself »
Checking for Errors
fetch() resolves when the server responds.
An HTTP error such as 404 Not Found does not reject the Promise.
Instead, check the ok property.
Example
// Async function to download a file
async function loadText() {
const response = await fetch("fetch.txt");
if (!response.ok) {
throw new Error(response.status + " " + response.statusText);
}
return await response.text();
}
Try it Yourself »
Handling Errors
Most fetch errors are not JavaScript errors.
They are most often path and response problems.
A common beginner mistake is expecting fetch to fail on Http errors like 404 or 500.
Fetch only rejects on network errors.
A 404 response is not a rejected promise.
You must check response.ok.
Use try...catch to handle errors.
Example
// Async function to download a file
async function loadText() {
try {
const response = await fetch("fetch.txt");
if (!response.ok) {
throw new Error(response.statusText);
}
myDisplayer(await response.text();
} catch(err) {
myDisplayer(err.message);
}
}
Try it Yourself »
The above example handles HTTP errors correctly.
If fetch is not working, check the console.
Then check the Network tab.
- Is the file path correct?
- Is the status code 200?
- Is the response JSON?
Loading Multiple Files
Independent downloads can run in parallel.
Example
// Async function to download files
async function loadData() {
const [customerResponse, productsResponse, newsResponse] = await Promise.all([
fetch("customer.json"),
fetch("products.json"),
fetch("news.json")
]);
const customer = await customerResponse.json();
const products = await productsResponse.json();
const news = await newsResponse.json();
myDisplayer("Custome name: " + customer.name);
myDisplayer(products.length + " products");
myDisplayer(news.length + " news items");
}
// Call the async function
loadData();
Try it Yourself »