AppDividend
Latest Code Tutorials

Javascript Fetch API Example Tutorial From Scratch

3

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.

If you do not know what promises then check out my following tutorials.

  1. Promise Reject Example
  2. Promise Resolve Example
  3. Promise All Example
  4. Promise Race Example

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 the 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 the 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 Stream object and 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 a 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 in Javascript

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.

#Response Metadata

In the above example, we have seen the status of a Response object and how to parse a response as JSON. We can access other metadata like headers. So see the following code.

fetch('users.json').then(function(response) {
    console.log(response.headers.get('Content-Type'));
    console.log(response.headers.get('Date'));

    console.log(response.status);
    console.log(response.statusText);
    console.log(response.type);
    console.log(response.url);
});

#Response Types

When we make a fetch request, the response will be given the response.type of “basic“, “cors” or “opaque“. These types show where a resource has come from and can be used to inform how we should treat a response object.

When the request is made for the resource on the same origin, the response will have the basic type and there aren’t any restrictions on what you can view from the response.

If the request is made for the resource on another origin which returns CORs headers, then the type is cors. The CORS and the basic responses are almost identical except that a cors response restricts the headers you can view to `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`.

An opaque response is for a request made for a resource on a different origin that doesn’t return CORS headers. With an opaque response we won’t be able to read the data returned or view the status of the request, meaning we can’t check if the request was successful or not.

You can define a mode for a fetch request such that only certain requests will resolve. The modes you can set are as follows:

  1. same-origin only succeeds for the requests for assets on the same origin, all the other requests will reject.
  2. The CORS will allow the requests for assets on the same-origin and other origins which return an appropriate CORS headers.
  3. The cors-with-forced-preflight will always perform a preflight check before making an actual request.
  4. The no-cors is intended to make the requests to other origins that do not have the CORS headers and result in an opaque, but as stated, this isn’t possible in the window global scope at the moment.

If we want to define the mode, add the options object as a second parameter in the fetch request and define a mode in that object.

// app.js

fetch('https://facebook.com/cors-enabled/some.json', {mode: 'cors'})
  .then(function(response) {
    return response.text();
  })
  .then(function(text) {
    console.log('Request successful', text);
  })
  .catch(function(error) {
    log('Request failed', error)
  });

#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 the 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+. So, we have used async-await in node.js.

#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.

One another option of the fetch API is to use the axios library. It is a third party very popular Javascript library.

In this blog, I have written the following tutorials on Axios using different frameworks.

  1. Axios Tutorial
  2. React Axios Example
  3. React Redux Axios Example
  4. Vue Axios Example

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

3 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?

  3. srinivas says

    hi can you please post how to display the fetch response in a web browser

Leave A Reply

Your email address will not be published.

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