JavaScript Fetch Function: A Comprehensive Guide
What is the Fetch Function?
The fetch
function is a built-in JavaScript API for making HTTP requests. It is used to fetch resources such as JSON, HTML, or plain text from a server. The function returns a Promise
, making it ideal for asynchronous operations.
Basic Syntax of Fetch
fetch(url, options)
.then(response => {
// Handle response
})
.catch(error => {
// Handle error
});
- url
: The URL of the resource to fetch. - options
: An optional object to configure the request.
Types of Errors in Fetch
The fetch
function handles errors differently compared to traditional XHR (XMLHttpRequest). Common error types include:
- Network Errors: Occurs when the request cannot reach the server (e.g., no internet connection).
- HTTP Errors: The
fetch
function does not throw an error for HTTP errors like 404 or 500. Instead, you need to check theresponse.ok
property. - Parsing Errors: Occurs when the response cannot be parsed as JSON.
Example of handling errors:
fetch('https://dummyjson.com/products')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
return response.json();
})
.catch(error => {
console.log('Error:', error.message);
});
The Options Object
The options
object allows you to customize the HTTP request. Common key-value pairs include:
Key | Description | Values |
---|---|---|
method |
Specifies the HTTP method. | GET , POST , PUT , DELETE , PATCH , etc. |
headers |
Custom headers to send with the request. | An object (e.g., { 'Content-Type': 'application/json' } ). |
body |
The body of the request, used with methods like POST or PUT. | A string (e.g., JSON.stringify(data) ). |
mode |
Controls the mode of the request. | cors , no-cors , same-origin |
credentials |
Indicates whether cookies should be sent with the request. | include , same-origin , omit |
cache |
Determines how the request should interact with the browser's cache. | default , no-cache , reload , force-cache , only-if-cached |
Example with Options
Hereβs an example using the options
object:
fetch('https://dummyjson.com/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'New Product',
price: 100
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Explanation:
method: 'POST'
: Specifies the HTTP method.headers
: Adds a custom header for content type.body
: Sends a JSON object as the request body.
Using Async/Await with Options
You can also use async/await
with the options
object for better readability:
async function postData() {
try {
let response = await fetch('https://dummyjson.com/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'New Product',
price: 100
})
});
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error.message);
}
}
postData();
Conclusion
The fetch
function is a versatile and powerful tool for making HTTP requests. By understanding its error handling, options, and configurations, you can effectively interact with APIs and build robust web applications.