DEV Community

AndrewCabana
AndrewCabana

Posted on

Exploring JavaScript Fetch API

What is Fetch? JavaScripts fetch API is powerful yet simple promised based interace that allows web browers to make HTTP request to servers. Fetch request are similar to XMLHTTPrequest, however with the use of promises Fetch request offers a simpler solution that avoids using callbacks.

Sending a request
Below is a basic example of the fetch() method

  1. fetch('example url')
  2. .then(response => {
  3. // server response
  4. console.log(response);
  5. })
  6. .then(data => {
  7. // data from url
  8. console.log(data);
  9. })
  10. .catch(error => {
  11. //error handling
  12. });

This code uses the fetch method to make a network request to an example URL. It then uses the .then method to handle the response returned from the server and log it to the console.

Afterwards, it uses another .then method to handle the data returned from the previous step and log it to the console.

Lastly, it uses the catch method to handle any errors that may occur during the fetch request and log them to the console.

Init Options
the fetch() method has two paramaters that can be passed.The path to the resource is the first parameter and is required for the method to work properly. A second optinonal init paramater is used for futher options of the fetch() method.

  1. const initOptions = {
  2. method: "POST",
  3. headers: { 'content-Type' : 'application/json },
  4. body: JSON.stringify({ title: 'Example Fetch POST})
  5. };
  6. const response = fetch('example URL', initOptions);
  7. const data = response.json();

in the code example above we are saving the options of our request to a const variable initOptions and passing this variable as the second paramater in our request. When creating request options there is plenlty of options to adjust a few are listed below

  • Method - sets request method to GET or Post.
  • Headers - add headers to the request.
  • Mode - request mode (cors, no-cors, or same-origin).
  • Cache - string that determines how a request will interact with a browser.

  • Credentals - what browsers do with credentials.

Additional fetch() init options and how to use them can be found here
https://developer.mozilla.org/en-US/docs/Web/API/fetch

Response Error Handling
Errors with HTTP request are handled with the response object properties. Response.ok and Response.status are two propeties returned that are usufal in error handling. Response.ok represents a boolean value to represent a successful response. Response.status will display HTTP codes 200 for success and a 404 code if no resource was found. Heres a look at a response object from www.boredapi.com. Response.ok is true and Response.status is 200 showing a successful request

Image description

JavaScript fetch API is an excellent tool for handling HTTP requests, and its simplicity makes it easy to use. By using fetch, we can fetch data from the server, send data to the server, and handle errors with ease.

Top comments (0)