How to use the Fetch API in JavaScript
Welcome to the confusing world of JavaScript! If you're looking to improve your server data retrieval skills, you've come to the right place. Today we'll take a closer look at the Fetch API, a modern, powerful tool for making HTTP requests in JavaScript.
Why choose Fetch API over traditional methods
In the old days, the XMLHttpRequest method was used to request data. But we must admit that this method is now outdated. It's bulky, requires more lines of code, and uses a callback pattern that isn't as simple as the newer promise-based framework. The Fetch API offers a much more modern way to interact with the server. This native JavaScript API is promise-based, meaning it uses promises to handle results and failures, making the code more readable and manageable.
Moreover, it allows you to use modern async/await syntax to create even cleaner and more intuitive code. The Fetch API is built into the JavaScript language, so you don't need to rely on external libraries like Axios or jQuery. This simplifies the chain of dependencies in a project and makes troubleshooting clearer.
Syntax basics: Breaking it down
When we talk about the Fetch API, one of the first things that comes to mind is the simplicity of its syntax. In the simplest case, you need to specify the URL from which you want to get the data. Here's what the syntax looks like in its simplest form:
fetch('https://api.example.com/data')
This piece of code essentially asks the browser to go to the specified URL and fetch the data . The function returns a Promise that resolves to a Response object representing the completed request. Note that only the URL is required, which makes working with Fetch easier.
GET request: Your first request
Retrieving data from the server is one of the most common operations in web development. A GET request serves this purpose. To perform a GET request, just call the fetch function indicating the URL of the resource that needs to be retrieved. After receiving the data, you can convert it to JSON format for easier work with it.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log( data))
This code gets data from a given URL, converts the resulting payload into JSON and prints it to the console. The then method determines what to do after the Promise resolves. This is a chained method, meaning you can attach another then method to handle subsequent actions.
Handling HTTP responses
Fetch does not reject promise for server error status codes. Thus, it becomes necessary to check the ok property of the Response object to ensure that the request was successful. If this is not done, the application may not behave as expected.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.log('There was a problem with the fetch operation:', error));
This piece of code not only receives data, but also checks whether the server responded without errors. It's always a good idea to check for errors to make sure you're not working with low-quality data. The catch method will handle any errors related to network problems or the entered URL.
POST request: Sending data
While a GET request retrieves data, a POST request sends it to the server. To make a POST request using Fetch, you can add a settings object as the second argument to the Fetch function. The settings object allows you to specify the method, headers, and body of the request.
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application /json'
},
body: JSON.stringify({key: 'value'})
});
Here the property method indicates that we are making a POST request. The headers property sets the content type as JSON, and the body property contains the payload we want to send, also in JSON format. This configuration ensures that both the client and server understand the data being sent.
Working with Headers
Adding headers to a Fetch request can be critical when working with APIs that require authentication or special content types. Fetch makes it easy to add headers. You can include them in the options object using the headers key.
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer ' + token
}
})
The above code adds the Authorization header to pass the token for authenticated routes. Headers can also be used to control cache, specify content types, control CORS (Cross-Origin Resource Sharing) restrictions, etc.
Using Query Parameters
Adding query parameters to URLs in Fetch is a common requirement. You can manually concatenate the parameters into the URL, or use the native JavaScript URL and URLSearchParams classes to add them programmatically.
let url = new URL('https://api.example.com/data'),
params = {id: 123, name: 'John'}
Object.keys( params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url);
This way, you can add as many query parameters as you need without having to worry about manually coding them or making syntax errors in the URL string. This improves the readability and maintainability of the code.
Request and Response Objects
Fetch provides specialized Request and Response objects for advanced use cases. You may need to create a Request object if you want to control certain settings, such as caching. This object can then be passed as an argument to fetch .
let req = new Request('https://api.example.com/data', { method: 'GET', cache: 'reload' });
fetch(req);
Using the Request and Response objects allows you to fine-tune various aspects of the request-response cycle, such as customizing headers or content types for each request. This opens up the possibility of creating complex configurations that a simple Fetch call might not account for.
Async/Await with Fetch
While the Fetch API with promises is clean, you can make it even cleaner by using async/await. This makes the code more readable and easier to understand, especially if you're dealing with a series of asynchronous operations.
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
Here the function async fetchData makes an asynchronous call using await which causes the function to execute until the Promise resolves. Once the data is received, it is converted to JSON and output to the console.
Aborting fetch
The disadvantage of Fetch is that it cannot cancel a request once it has been initiated. However, the Fetch API offers the AbortController interface for aborting fetch requests.
const controller = new AbortController();
const { signal } = controller;
fetch('https://api.example.com/data', { signal })
.catch(err => {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
}
});
controller.abort();
By associating the AbortController signal with the sample, you can later call controller.abort() to cancel the request. This feature is useful for scenarios in which you need to provide users with the ability to cancel long-running queries.
Browser Support: What You Need to Know
The Fetch API is supported by most modern web browsers, including Chrome, Firefox and Safari. However, it is worth noting that it is not supported in Internet Explorer. If you're aiming for broad compatibility, you may need to enable a polyfill for browsers that don't support Fetch.