Javascript Fetch API Example | How to Use the Fetch API

Javascript fetch() is an inbuilt API that provides an interface for fetching resources. Using fetch(), we can send 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, 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.

Javascript fetch allows you to make network requests similar to XMLHttpRequest (XHR).

The main difference is that the Javascript 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 How to Use the Fetch API in Javascript.

Javascript Fetch API

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

Javascript fetch method only has one mandatory argument, which is the URL of the resource you wish to fetch.

Syntax

let promise = fetch(URL, [options])

Parameters

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 the 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 don’t have a body yet.

The promise rejects if the fetch() was unable to 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 the error.

We can see HTTP-status in response properties:

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

XMLHttpRequest

An XMLHttpRequest would need two listeners to be set 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; } }; xhttp.open("GET", "filename", true); xhttp.send();

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

You can do the following stuff.

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

#Requests

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

method – GET , POST , PUT , DELETE , HEAD

, , url – URL of the request

headers – associated Headers object

referrer – referrer of the request

mode – cors , no-cors , same-origin

, , credentials – should cookies go with the request? omit , same-origin

redirect – follow , error , manual

, , integrity – subresource integrity value

cache – cache mode ( default , reload , 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.

case arrayBuffer() – In here, we return a promise that resolves with an ArrayBuffer.

blob() – This is one determines with a Blob.

formData() – It also returns a promise but one that 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:

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 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. 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" ” “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 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 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 status of the request, meaning we can’t check if the request was successful or not.

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

A same-origin only succeeds for the requests for assets on the same origin, and all the other requests will reject. The CORS will allow the requests for assets on the same-origin and other origins which return appropriate CORS headers. The cors-with-forced-preflight will always perform a preflight check before making an actual request. 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 has, get, set, 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));

#Fetch Post Request

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 a node version of the fetch request called node-fetch. Remember, some modules exist at the 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 as below.

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 multiple attributes:

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

Then use it 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.

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

Conclusion

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

For example, we can use the network request to:

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

TThere’san 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 a modern and versatile, so that we will start with it. It’s not supported by the old browsers, but very well supported among the modern ones.

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

Finally, Javascript Fetch API Example Tutorial is over. Thanks for reading this post.