Fetch is a JavaScript interface that allows you to make network requests to retrieve and send data between a web browser and a server.

The basic syntax of using the Fetch API is as follows:

fetch(url, options)
    .then(response => {
        // handle the response
    })
    .catch(error => {
        // handle any errors
    });

The fetch() function takes two parameters: the URL of the resource you want to fetch and an optional object that allows you to customize the request.

GET Request

To make a GET request, you can use the fetch function with the URL you want to retrieve data from.

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // Parse the response body as JSON
  })
  .then(data => {
    // Use the fetched data
    console.log(data);
  })
  .catch(error => {
    // Handle any errors that occurred during the fetch
    console.error('Fetch error:', error);
  });

In this code:

  • We start by calling fetch with the URL.
  • The fetch function returns a Promise that resolves to the Response object representing the response to the request.
  • We check if the response was successful (status code 200-299). If not, we throw an error.
  • We parse the response body as JSON using response.json().
  • Finally, we use the fetched data in the second .then block, and we handle any errors in the .catch block.

POST Requests

To send data to the server using a POST request, you can specify the HTTP method and include an object with request options, including the method and body properties.

const dataToSend = { name: 'John', age: 30 };

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

In this code:

  • We specify the method as ‘POST’ to indicate that it’s a POST request.
  • We set the Content-Type header to 'application/json' to indicate that we’re sending JSON data.
  • We use JSON.stringify() to convert the JavaScript object into a JSON string for the request body.

These are just a few examples of how you can use the Fetch in JavaScript. The Fetch API provides many more options and methods that allow you to customize your requests and handle response data.

For more information, you can refer to the official documentation and the various online resources available.