MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  • AJAX
  • XMLHttpRequest
  • Fetch
  • Fetch Interfaces
  • Making a request using fetch()
  • The Response Object
  • Headers Object
  • Supplying options to fetch()
  • Request Object
  • Conclusion
  1. 2nd Month
  2. Week 5
  3. REST - Representational State Transfer

The Fetch API

A modern replacement for XMLHttpRequest

PreviousFetching data from the serverNextCross-Origin Resource Sharing (CORS)

Last updated 1 year ago

fetch

It is said that “Necessity is the mother of all inventions” and that’s what fueled the development of Fetch API. But before digging deeper into the Fetch API let’s dive into the history behind it. I know I know what’s going on in your mind but I will keep it short.

AJAX

Before AJAX (Asynchronous JavaScript and XML) concept was introduced, to update the portion of a page, browsers at that time used to make a request for a full web page to the server, after the request was received by the server, it used to create and return a page to the browser as a response. It means that even for a small change the page was loaded entirely. That was bad right? very very bad. After AJAX came into the world of internet, it changed the traditional way of updating the page. With AJAX, Web applications were able to send and retrieve data from a server asynchronously (in the background) without interfering with the display and behaviour of the existing page.

XMLHttpRequest

In 2006 the World Wide Web Consortium published a Working Draft specification for the XMLHttpRequest object. XMLHttpRequest object is used to retrieve data from a server asynchronously. Wait for a second, what did you just said, yes you heard it clearly. In the initial stages, XMLHttpRequest used to fetch XML data over HTTP hence the name. But today it can be used with protocols other than HTTP and it can fetch data not only in the form of XML but also JSON, HTML or plain text.

The original concept behind the XMLHttpRequest object was originally created by the developers of Outlook Web Access (by Microsoft).

So let’s try with an example, we will make a simple request using XMLHttpRequest, get a response and parse it as JSON.

We need two listeners to be set to handle the success and error cases and a call to open() and send(). The response from the server is stored in the responseText variable, which is converted to JavaScript object using JSON.parse().

We have used XMLHttpRequest for several years to request data other than XML, and that’s where the confusion starts when beginner try to learn how to make an asynchronous request in JavaScript.

Isn’t there a cleaner and simple API to make an asynchronous request? well yes, there is and for that, we need to get back to present. So Let’s get back to the present.

Fetch

Fetch Interfaces

The Fetch API has following interfaces

Making a request using fetch()

The Response Object

The above code makes use of Fetch API and makes a call to GitHub to fetch data about the user. When the promise is resolved we get a Response object in return. But wait, if you try logging Response object on the console you will find that it didn’t have the data which we want. That’s because a Response object has information about the response itself. To actually get the data, we need to get the body of the response.

Since the Github API we’re using will return JSON to us, the returned response will have .json() method. We just need to call .json() on the response variable. The .json() method on a Response object returns a Promise, so we need to chain on another .then().

Headers Object

Supplying options to fetch()

The fetch() method accepts an optional second parameter, an init object that allows you to customise the request.

Request Object

Conclusion

Definitely, XMLHttpRequest wasn’t made for the things we are using it today. Also, it’s API is kinda messed. The Fetch API makes it easier to make asynchronous requests and handle responses better than using an XMLHttpRequest. Fetch allows us to create a better API for the simple things, using modern JavaScript features like promises.

Let’s start fetching !!

Fetch is a new native JavaScript API, supported by most browsers today. Fetch allows you to make network requests similar to XMLHttpRequest. According to Fetch makes it easier to make asynchronous requests and handle responses better than with the older XMLHttpRequest. It is an improvement over the XMLHttpRequest API. The main difference between Fetch and XMLHttpRequest is that the Fetch API uses Promises, hence avoiding callback hell.

If you are new to promises then check out . You can make use of for .

: The fetch() method used to fetch a resource.

: Represents response/request headers, allowing you to query them and take different actions depending on the results.

: Represents a resource request.

: Represents the response to a request.

A function is available in the global window object. The fetch() function takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise, whether it is successful or not. If request is successful .then() function will receive Response object, if request fails then .catch() function will receive an error object

Response object
Extracted JSON object from Response body

The Headers interface allows you to create your own headers object via the constructor. A headers object is a collection of name-value pairs.

The Request Object represents a resource request. Instead of passing an URL of the resource into the fetch() call, you can create a request object using the constructor, and pass that as an argument to fetch(). By passing Request object to the fetch(), you can make customised requests.

2️⃣
Google Developers Documentation
JavaScript Promises: an Introduction
polyfill
browsers that are not currently supported
fetch()
Headers
Request
Response
fetch()
Headers()
Request()