DEV Community

Cover image for Fetch API in JavaScript
Sakib Ahmed
Sakib Ahmed

Posted on

Fetch API in JavaScript

Basic Fetch request

fetch(url)
.then(response=> response.json())
.then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

This is how to fetch in javascript. Very simple!

Wait not done yet.

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. Before fetch(), we used XHR (XMLHttpRequest). Using Fetch is very easy. Fetch() starts the process of fetching a resource from a server and returns Promise that resolves to a Response object.
So we dont need XMLHttpRequest anymore. But yeah, we need xhr for ajax.

But how XMLHttpRequest is look like? how to write ?
Lets see:

// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();

// Define a callback function
xhttp.onload = function() {
  // Here you can use the Data
}

// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Enter fullscreen mode Exit fullscreen mode

fetch()

fetch('http://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data));
Enter fullscreen mode Exit fullscreen mode

Here we are fetching a JSON file from our desire server and printing it to the console. The simplest use of fetch() takes one argument β€” the path to the resource you want to fetch β€” and does not directly return the JSON response body but instead returns a promise that resolves with a Response object.

The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON.

Real Example:

Fetch url: https://my-json-server.typicode.com/typicode/demo/posts

fetch('https://my-json-server.typicode.com/typicode/demo/posts')
  .then((response) => response.json())
  .then((data) => console.log(data[0].id));
// output: 1
Enter fullscreen mode Exit fullscreen mode

Go to the link. We are fetching json from this url.

Image description

for more example, check my codepen code FETCH "BRAKING BAD" CHARACTER

Top comments (0)