The Fetch API is a modern interface that allows you to make network requests in JavaScript. It is a powerful alternative to the older XMLHttpRequest
and is widely used for interacting with REST APIs or fetching resources like JSON, text, or HTML from a server.
Why Use the Fetch API?
- Simpler Syntax: Based on promises, making asynchronous code easier to read and write.
- Built-In: Available in most modern browsers without additional libraries.
- Flexible: Supports various HTTP methods (GET, POST, PUT, DELETE, etc.).
- Streaming Support: Handles large files more efficiently with streams.
Fetch Syntax
fetch(url, options)
.then(response => {
// Handle response
})
.catch(error => {
// Handle error
});
Parameters:
url
: The resource to fetch.options
(optional): Configuration object for the request, including method, headers, body, etc.
Basic Usage Example
fetch('https://api.example.com/data')
.then(response => response.json()) // Parse JSON from the response
.then(data => console.log(data)) // Use the data
.catch(error => console.error('Error:', error));
Fetch API with POST Request
To send data to a server, include the method
and body
in the options object.
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'John', age: 30 }),
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
Handling Errors
The Fetch API does not automatically throw errors for HTTP error statuses (e.g., 404 or 500). You need to check the response.ok
property.
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('Error:', error));
Fetch API Features
- CORS (Cross-Origin Resource Sharing):
- Fetch follows CORS policies by default, allowing or restricting cross-origin requests.
- Stream Support:
- Fetch can handle large data streams efficiently using the
body
property.
- Fetch can handle large data streams efficiently using the
Example: Reading a Response Stream
fetch('https://api.example.com/data')
.then(response => response.body)
.then(stream => {
const reader = stream.getReader();
return new ReadableStream({
start(controller) {
function push() {
reader.read().then(({ done, value }) => {
if (done) {
controller.close();
return;
}
controller.enqueue(value);
push();
});
}
push();
},
});
})
.then(stream => new Response(stream))
.then(response => response.text())
.then(data => console.log(data));
Fetch with Async/Await
Using async/await
makes the code cleaner and easier to read:
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('Error:', error);
}
}
fetchData();
Advanced Fetch: Custom Headers
Add custom headers for authentication or other needs:
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer your-token-here',
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Comparison to XMLHttpRequest
Feature | Fetch API | XMLHttpRequest |
---|---|---|
Ease of Use | Promise-based syntax | Callback-based |
Response Types | Streams, Blob, JSON, etc. | Text, JSON, XML |
CORS Handling | Automatic | Manual |
Built-in Support | Yes | Yes |
Conclusion
The Fetch API is an essential tool for modern web developers. Its simplicity, flexibility, and ability to work with promises make it a powerful replacement for traditional methods like XMLHttpRequest
. Start leveraging Fetch in your projects today for a cleaner, more efficient codebase.
For more tutorials and guides, visit The Coding College.