The Fetch API is a modern, powerful interface for making network requests from web browsers. It provides a global fetch() method that allows you to perform HTTP requests to servers and retrieve data asynchronously. This tutorial will cover the basics of using the Fetch API, including how to make GET and POST requests, handle responses, manage errors, and apply best practices.
The Fetch API is built on top of Promises, making it easier to write asynchronous code compared to older methods like XMLHttpRequest. It supports all modern browsers and provides a more flexible and powerful way to interact with web resources.
To use the Fetch API, you simply call the fetch() function with a URL. This function returns a Promise that resolves to the Response object representing the response of the request.
// Example: Fetching data from an API
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json(); // Parse JSON response into native JavaScript objects
})
.then(data => {
console.log(data); // Handle the data received from the server
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
// Example: Sending data to an API
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' }) // Convert JavaScript object to JSON string
})
.then(response => response.json())
.then(data => {
console.log(data); // Handle the response data
})
.catch(error => {
console.error('Error:', error);
});
The Response object provides several methods and properties to handle the server's response:
response.ok: A boolean indicating whether the request was successful (status in the range 200–299).response.status: The status code of the response.response.statusText: The status message corresponding to the status code.response.headers: Contains the headers of the response.response.json(): Parses JSON body of the response and returns a Promise that resolves with the result.fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Fetch error:', error);
});
Errors can occur due to network issues, invalid URLs, or server errors. It's important to handle these gracefully.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
fetchData();
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
fetchData();
For large files or streams, you can use the ReadableStream interface to process data as it arrives.
fetch('https://api.example.com/largefile')
.then(response => response.body.getReader())
.then(reader => {
const decoder = new TextDecoder();
let done;
let chunk;
(function read() {
reader.read().then(({ value, done: readingDone }) => {
if (readingDone) {
console.log('Stream complete');
return;
}
chunk = decoder.decode(value);
console.log(chunk);
read();
});
})();
})
.catch(error => {
console.error('Fetch error:', error);
});
You can customize requests by setting headers, credentials, and other options.
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Custom-Header': 'Value'
},
credentials: 'include' // Include cookies with the request
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Fetch error:', error);
});
The Fetch API is a versatile and powerful tool for making network requests in JavaScript. By understanding how to use it effectively, you can build robust web applications that interact with external resources efficiently. Whether you're fetching data from APIs or uploading files, the Fetch API provides the flexibility and control needed to handle these tasks seamlessly.
Remember to always check response statuses, handle errors gracefully, and use best practices to ensure your application is both efficient and reliable.