AppDividend
Latest Code Tutorials

Javascript Fetch API Example Tutorial From Scratch

2

Javascript Fetch API Example Tutorial From Scratch is today’s main topic. The Fetch API provides an interface for fetching resources. We all remember the dreaded XMLHttpRequest we used back in the day to make requests; it involved some messy code, it didn’t give us promises and let’s be honest, it wasn’t pretty JavaScript, right? If you were using jQuery, then you have used the cleaner syntax with jQuery.ajax(). Well, JavaScript has it is own built-in neat way now.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

The fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a more straightforward and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest. Although we can also use an async-await feature of es7 to get rid of promise as well and it will work as a plain javascript function, but the promise is also a way to send the request and receive a response. In this article, I will give you a brief introduction about Javascript Fetch API Example Tutorial.

# Javascript Fetch API Example Tutorial

A Fetch API provides a fetch() method defined on a window object, which you can use to perform requests and sent it to the server. This method returns a Promise that you can use to retrieve the response of the request. Generally, we use GET and POST method to send a network request to the server and retrieve the response and then display that response in the proper format to the User. The fetch() method only has one mandatory argument, which is the URL of the resource you wish to fetch.

#Requests

Request instance represents the requested piece of a fetch() call. By passing fetch Request, you can make advanced and customized requests:

  • method – GETPOST, PUTDELETEHEAD
  • url – URL of the request
  • headers – associated Headers object
  • referrer – referrer of the request
  • mode – corsno-cors, same-origin
  • credentials – should cookies go with the request? omitsame-origin
  • redirect – followerror, manual
  • integrity – subresource integrity value
  • cache – cache mode (defaultreload, no-cache)

#GET Requests

Straightforwardly, all you do is to call fetch with the URL you want, by default the Fetch API uses the GET method so that a direct call would be like this.

fetch('https://api.github.com/users/KrunalLathiya')
.then(response => response.json())
.then(data => {
  console.log(data) // Prints result from `response.json()` in getRequest
})
.catch(error => console.error(error))

Here, we get a response, and the response is an object but, the response we get is not JSON but a simple Javascript object with a series of methods that we can use further to process our data whichever way we want.

  • clone() – This method implies this method creates a clone of the response.
  • json() – This method resolves the promise with JSON.
  • redirect() – This method creates the new response but with a different URL.
  • text() – In this case, it resolves with a string.
  • arrayBuffer() – In here we return a promise that resolves with an ArrayBuffer.
  • blob() – This is one determines with a Blob.
  • formData() – Also returns a promise but one that determines with FormData object.

Loading JSON

Let us see how we can extract the JSON data from that response once the request completes:

fetch('https://api.github.com/users/KrunalLathiya')
.then(res => res.json())
.then(json => console.log(json));

So here when the HTTP request ends, we get a promise with a data, and then we resolve that promise with JSON. First, we start the request by calling fetch(), and when the promise is fulfilled, it returns a Response object, which exposes a json method.

However, the json() method also returns a promise, which means we need to chain on another then(), before the JSON response is logged to the console.

Request Headers

fetch('https://api.github.com/users/KrunalLathiya', {
  headers: new Headers({
    'User-agent': 'Mozilla/4.0 Custom User Agent'
  })
})
.then(response => response.json())
.then(data => {
  console.log(data)
})
.catch(error => console.error(error))

The ability to set request headers is essential to request flexibility. You can work with request headers by executing new Headers():

// Create an empty Headers instance
let headers = new Headers();

// Add a few headers
headers.append('Content-Type', 'text/plain');
headers.append('X-My-Custom-Header', 'CustomValue');

// Check, get, and set header values
headers.has('Content-Type'); // true
headers.get('Content-Type'); // "text/plain"
headers.set('Content-Type', 'application/json');

// Delete a header
headers.delete('X-My-Custom-Header');

// Add initial values
let headers = new Headers({
	'Content-Type': 'text/plain',
	'X-My-Custom-Header': 'CustomValue'
});

You can use the append the hasgetset, and delete methods to modify request headers.

Advanced: CORS example

CORS is primarily checked at the server to make sure your configuration is correct on the server-side.

The credentials option controls if your cookies are automatically included.

fetch('https://api.github.com/users/KrunalLathiya', {
  credentials: 'include', // Useful for including session ID (and, IIRC, authorization headers)
})
.then(response => response.json())
.then(data => {
  console.log(data) // Prints result from `response.json()`
})
.catch(error => console.error(error));

#Post Requests

postRequest('https://appdividend.com/api/v1/users', {user: 'Krunal'})
  .then(data => console.log(data)) // Result from the `response.json()` call
  .catch(error => console.error(error))

function postRequest(url, data) {
  return fetch(url, {
    credentials: 'same-origin', // 'include', default: 'omit'
    method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
    body: JSON.stringify(data), // Coordinate the body type with 'Content-Type'
    headers: new Headers({
      'Content-Type': 'application/json'
    }),
  });
  .then(response => response.json())
}

Here, we have created a postRequest function and passed the two parameters. The first parameter is the request and the second parameter is the data that needs to be stored on the server.

#Node.js Fetch Request Example

If you are using Node.js, then you need to install node version of fetch request called node-fetch. Remember there are some modules which exist at browser and node server like a console. But in some modules are installed explicitly for the client like fetch is by default in the browser but it is not already there in the node.js. So we need to install it as a third party. The example of that is below.

// server.js

const fetch = require('node-fetch');

async function getGithubData()
{
  let data = await fetch('https://api.github.com/users/KrunalLathiya');
  let main = await data.json();
  console.log(main);
}

getGithubData();

Here, you can get the output like below.

Javascript Fetch API Example Tutorial From Scratch

 

In this example, we have to get rid of promise and use the latest ES7 feature called async-await. Async functions are supported in all the modern browsers (not IE or Opera Mini) and Node.js 7.6+.

#Uploading files using Fetch Request

postFile('https://appdividend.com/api/v1/users', 'input[type="file"].avatar')
  .then(data => console.log(data))
  .catch(error => console.error(error))

function postFile(url, fileSelector) {
  const formData = new FormData()
  const fileField = document.querySelector(fileSelector)
  
  formData.append('username', 'abc123')
  formData.append('avatar', fileField.files[0])

  return fetch(url, {
    method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
    body: formData  // Coordinate the body type with 'Content-Type'
  })
  .then(response => response.json())
}

Here, we have merely passed the reference to the file field and append that file to the formData and send the post request to the server.

Uploading multiple files

Setup a file upload element with a multiple attribute:

<input type='file' multiple class='files' name='files' />

Then use with something like:

postFile('https://appdividend.com/api/v1/users', 'input[type="file"].files')
  .then(data => console.log(data))
  .catch(error => console.error(error))

function postFile(url, fileSelector) {
  const formData = new FormData()
  const fileFields = document.querySelectorAll(fileSelector)

  // Add all files to formData
  Array.prototype.forEach.call(fileFields.files, f => formData.append('files', f))
  // Alternatively for PHP peeps, use `files[]` for the name to support arrays
  // Array.prototype.forEach.call(fileFields.files, f => formData.append('files[]', f))
  
  return fetch(url, {
    method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
    body: formData  // Coordinate the body type with 'Content-Type'
  })
  .then(response => response.json())
}

You can find more on fetch on this link.

Finally, Javascript Fetch API Example Tutorial From Scratch tutorial is over. Thanks for taking this post and have a beautiful day.

2 Comments
  1. labike says

    if interface API return customer status, for example:

    res.status == 0
    .then(/*handle something*/)

    or

    res.status == 1
    .then(/*handle something*/)

    or

    res.status == 2
    .then(/*handle something*/)

    in Fetch, how to resolve?

  2. Arshad says

    Nice article Krunal. One question rather doubt, is is necessary to handle error scenario with catch block here or we can pass this ownership to calling method?

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.