JavaScript use fetch API to make HTTP Requests

Hello dev's, today I'll show you how to use JavaScript's fetch API to make HTTP request. JavaScript's fetch API is a modern way of making HTTP requests in JavaScript, providing an easy-to-use interface for making asynchronous requests So, let's see how we can use JavaScript fetch API to make HTTP requests in our project.

Example of Fetch API

Fetch API is one of the best replacement of ajax() or axios() call for calling the third part API's. JavaScript fetch API supports all other features that are available/we can use with ajax() or axios() call. Suppose, we want to make a request using POST method, we can use it like below with fetch API.

const data = { name: 'John Doe', email: '[email protected]' };

fetch('https://api.example.com/user', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

In this example, we're making a POST request to https://api.example.com/user with JSON data. We specify the request method and set the Content-Type header to application/json. We also stringify the data and pass it in the body option.

Note that the fetch() method returns a Promise, which is why we're chaining then() and catch() methods. We can use this pattern to make multiple requests and handle errors gracefully.
Even we can use the formData as well. Let's look at the below example.

const formData = new FormData();

formData.append("title", "My Vegas Vacation");

fetch('https://api.example.com/user', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

As we can see, we can even submit our form with the Fetch API. And also we didn't need any plugins or CDN links to work with fetch API. So, not only post request, we can make any request that modern HTTP requests support For more info about Fetch API, I suggest you to go through this link.

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. ๐Ÿ™‚