Javascript fetch: How to use fetch() Function

fetch api example tutorial

Javascript fetch allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Javascript Fetch API uses Promises, enabling a more straightforward and cleaner API, avoiding callback hell, and remembering the complex API of XMLHttpRequest.

Although we can also use an async-await feature of ES7 to get rid of promise, and it will work as a simple Javascript function, the promise is also a way to send the request and receive a response.

If you do not know what promises, check out the following tutorials.

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

In this article, I will give you a brief introduction about Using the Fetch API in Javascript.

Javascript fetch()

Javascript fetch() is a built-in function that provides an interface for fetching resources. The fetch method only has one mandatory argument: the URL of the resource you wish to fetch. Using fetch(), we can send an ajax request or network request to any server and get the json response.

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, you have used the cleaner syntax with jQuery.ajax(). Well, JavaScript has it is own built-in neat way now.

Generally, we use the GET and POST method to send a network request to the server, retrieve the response, and then display that response in the proper format.


let promise = fetch(URL, [options])


URL: the URL to access.
options: – optional parameters: method, headers, etc.

Without options, that is the simple GET request, downloading the contents of the url.

The browser starts the request right away and returns the promise that a calling code should use to get the final result.

Getting the response is usually a two-stage process.

First, the promise, returned by fetch() function, resolves with the object of the inbuilt Response class as soon as the server responds with headers.

At this stage, we can check the HTTP status to see whether it is successful or not check headers, but we don’t have a body yet.

The promise rejects if the fetch() could not make an HTTP request, e.g., network problems, or there’s no such site.

Abnormal HTTP statuses, such as 404 or 500, do not cause errors.

We can see HTTP-status in response properties:

  1. status – HTTP status code, e.g., 200.
  2. ok – boolean, true if the HTTP status code is 200-299.


An XMLHttpRequest would need two listeners to handle the success and error cases and a call to open() and send() function.

See the following code.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("demo").innerHTML = xhttp.responseText;
};"GET", "filename", true);

The XMLHttpRequest object can request the data from a web server.

 You can do the following stuff.

  1. Update the web page without reloading the page.
  2. Request data from the server – after the page has loaded.
  3. Receive data from the server  – after the page has loaded.
  4. Send data to the server – in the background.


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

  • url – The 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 in fetch()

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.

.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 a 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 the data way we want.

  • clone() – This method implies that this method creates a response clone.
  • 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() – Here, we return a promise that resolves with an ArrayBuffer.
  • blob() – This is one determined with a Blob.
  • formData() – It also returns a promise but determines with the FormData object.

Loading JSON in Javascript

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

.then(res => res.json())
.then(json => console.log(json));

When the HTTP request ends, we get a promise with 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 Javascript 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. In addition, we can access other metadata like headers. So visit the following code.

fetch('users.json').then(function(response) {


Response Types

When we make a fetch request, the response will be given the response.type of”basic"“”r” 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 of the exact 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, the cors type. The CORS and the necessary 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 request’s status, meaning we can’t check if the request was successful or not.

You can define the mode for a fetch request such that only specific 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, and all the other requests will reject.
  2. The CORS will allow the requests for assets on the same-origin and other origins which return 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('', {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('', {
  headers: new Headers({
    'User-agent': 'Mozilla/4.0 Custom User Agent'
.then(response => response.json())
.then(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

// 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 ensure your configuration is correct on the server-side.

The credentials option controls if your cookies are automatically included.

fetch('', {
  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 Request in fetch()

postRequest('', {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 fetch() Request Example

If you are using Node.js, you need to install a node version of the fetch request called node-fetch. Some modules exist at the browser and node server like a console. But 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. An example of that is below.

// server.js

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

async function getGithubData()
  let data = await fetch('');
  let main = await data.json();


Here, you can get the output as below.

Javascript Fetch API Example Tutorial From Scratch

We have to eliminate promises in this example and use the latest ES7 feature called async-await. Async functions are supported in 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('', '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 appended that file to the formData, and sent the post request to the server.

Uploading multiple files

Setup a file upload element with multiple attributes:

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

Then use it with something like:

postFile('', '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, f => formData.append('files', f))
  // Alternatively for PHP peeps, use `files[]` for the name to support arrays
  //, 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.

Instead of using fetch API, you can use the axios: Promise-based HTTP request library. It is a third-party, trendy Javascript library.


JavaScript can send the network requests to the server and load new information whenever needed.

For example, we can use the network request to:

  1. Submit an order,
  2. Load user information,
  3. Receive the latest updates from the server, And all of that without reloading the page!

Javascript Fetch API provides a fetch() method defined on a window object, which you can use to perform requests and send them to the server. This method returns a Promise that you can use to retrieve the response to the request.

There’s the umbrella term “JAX” (abbreviated Asynchronous JavaScript And XML) for network requests from JavaScript. We don’t have to use an XML, though: the term comes from old times; that’s why that word is there. You may have heard that term already.

There are multiple ways to send the network request and get information from the server.

The fetch() method is modern and versatile, so we will start with it. Unfortunately, it’s not supported by the old browsers, but very well supported among the modern ones.

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

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


  1. if interface API return customer status, for example:

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


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


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

    in Fetch, how to resolve?

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

Please enter your comment!
Please enter your name here

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