How to Use Fetch API in JavaScript to Make HTTP Requests

How to Use Fetch API in JavaScript to Make HTTP Requests How to Use Fetch API in JavaScript to Make HTTP Requests

The Fetch API is a modern, promise-based way to make HTTP requests in JavaScript. It has largely replaced older methods like XMLHttpRequest due to its cleaner syntax and powerful features. Whether you want to retrieve data from a server, submit form data, or interact with APIs, the Fetch API is essential for web developers.

In this guide, we’ll explore how to use the Fetch API effectively, covering everything from basic requests to advanced error handling.

What is the Fetch API?

Fetch API provides a global fetch() method that starts the process of fetching resources (like JSON, text, images) across the network. It returns a promise that resolves to the Response object representing the server’s response.

Unlike callbacks used in XMLHttpRequest, promises make it easier to write asynchronous code that is more readable and maintainable.

Making a Basic GET Request

The simplest use of Fetch is to retrieve data via a GET request. Here’s an example:

javascript
fetch('https://api.example.com/data')
.then(response => response.json()) // Parse JSON from response
.then(data => {
console.log(data); // Use the data from the API
})
.catch(error => {
console.error('Error fetching data:', error);
});

In this example, fetch() requests the URL, then converts the response to JSON, then handles the data. Errors are caught in the catch block.

Handling Different Response Types

The Response object provides several methods to handle different content types:

  • response.json() – Parses JSON data

  • response.text() – Returns plain text

  • response.blob() – For binary data (e.g., images)

  • response.formData() – For form data

  • response.arrayBuffer() – For low-level binary data

Example:

javascript
fetch('https://example.com/image.png')
.then(response => response.blob())
.then(imageBlob => {
// Create a local URL for the image blob and set it as an image source
const imgURL = URL.createObjectURL(imageBlob);
document.querySelector('img').src = imgURL;
});

Making POST Requests with Fetch

Fetch supports various HTTP methods, such as POST, PUT, DELETE. To send data, you must include a configuration object with method, headers, and body.

Example of a POST request sending JSON data:

How to Use Fetch API in JavaScript to Make HTTP Requests
How to Use Fetch API in JavaScript to Make HTTP Requests
javascript
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'Alice', age: 30 })
})
.then(response => response.json())
.then(data => console.log('User created:', data))
.catch(error => console.error('Error:', error));

Using Async/Await with Fetch

For cleaner asynchronous code, use async/await:

javascript
async function getData() {
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);
}
}

getData();

This approach makes it easier to read and write asynchronous fetch operations.

Handling HTTP Errors

Fetch only rejects promises for network errors, not for HTTP error statuses like 404 or 500. Therefore, you must check response.ok or response.status manually.

Example:

javascript
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Setting Request Headers

You can customize headers for authentication, content type, and more using the headers option:

javascript
fetch('https://api.example.com/protected', {
headers: {
'Authorization': 'Bearer your_token_here',
'Accept': 'application/json'
}
});

Cancelling a Fetch Request

You can cancel ongoing fetch requests using the AbortController API:

javascript
const controller = new AbortController();

fetch('https://api.example.com/longtask', { signal: controller.signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Fetch error:', error);
}
});

// Cancel the request after 3 seconds
setTimeout(() => controller.abort(), 3000);

Conclusion

The Fetch API offers a flexible and modern way to handle HTTP requests in JavaScript. Whether you’re performing simple GET requests or complex POST requests with headers and error handling, mastering Fetch is essential for frontend and full-stack developers. Its promise-based nature and integration with async/await make asynchronous code more readable and maintainable.