JavaScript Fetch API
The Fetch API interface lets you download (fetch) data from a web server.
await fetch() is the modern API for fetching data from an HTTP server.
XMLHttpRequest() was the old legacy API for fetching data from an HTTP server.
What is Fetch API
JavaScript Fetch API is a modern browser interface used to make asynchronous network requests to web servers.
Fetch is an easier and more powerful replacement for the older XMLHttpRequest object.
Fetch is uses standard JavaScript Promises for cleaner asynchronous code.
Fetching a Text File
The simplest way to demonstrate fetch() is to download a text file.
Examples
// Fetch a file
fetch(file)
.then(function(response) {
return response.text();
})
.then(function(data) {
myDisplayer(data);
});
Try it Yourself »
Or (using arrows)
// Fetch a file
fetch(file)
.then(response => response.text())
.then(data => myDisplayer(data));
Try it Yourself »
Note that .then() expects a function as its argument, so you must write .then(...), not .then {...}.
Using an Asynchronous Function
// Async function to fetch a file
async function loadText(file) {
const response = await fetch(file);
myDisplayer(await response.text());
}
Try it Yourself »
The Response Object
The fetch() method returns a Promise that resolves to a Response object.
The Response object contains information (properties) about the server response.
| Property | Description |
|---|---|
| ok | True if the request succeeded |
| status | The HTTP status code |
| statusText | The HTTP status message |
| url | The HTTP url address |
Example
The result is a Response object [object Response].
// Async function to download a file
async function loadText(file) {
const response = await fetch(file);
myDisplayer(response);
}
Try it Yourself »
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 »
Asynchrounous Output
JavaScript can continue running while waiting for the server to respond.
Example
// Async function to download a file
async function loadText(file) {
const response = await fetch(file);
myDisplayer(response.url);
}
loadText("fetch.txt");
myDisplayer("JavaScript continues.");
Try it Yourself »
Note
"JavaScript continues." is displayed first.
It is displayed while loadText() waits for fetch() to resolve.
Response Object Methods
The Response object has methods to read the server response.
| Method | Description |
|---|---|
| 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 |
Checking for HTTP Errors
fetch() resolves when the server responds.
A common beginner mistake is expecting fetch() to fail on Http errors.
An HTTP error such as 404 Not Found does not reject the Promise.
Fetch only rejects on network errors.
A 404 response is not a rejected promise.
You should always check the ok property.
Example
async function loadText(file) {
const response = await fetch(file);
if (!response.ok) {
myDisplayer(response.status + " " + response.statusText);
return;
}
myDisplayer(await response.text());
}
Try it Yourself »
Note
Most fetch errors are not JavaScript errors.
They are most often path and response problems.
If fetch is not working, check the console.
Then check the Network tab.
- Is the file name correct?
- Is the file path correct?
- Is the status code 200?
Fetch API vs. XMLHttpRequest (XHR)
| Feature | Fetch | XHR |
|---|---|---|
| Syntax | Promise-based | Callback-based |
| Error Handling | Rejects on network failure | Needs manual checking |
| Streams | Supports streams | Does not support streams |