Skip to main content

Command Palette

Search for a command to run...

What the heck is Fetch Request </>

Published
0 min read
fetch(url)

Hi, If you stumble upon this article you might have been wondering what Fetch is in Javascript. Yoo gear up you're about to get everything you know.. ::)

So let's get to business, There are asynchronous ways of fetching and sending requests to the server, There are numerous ways of doing that of which fetch is included. Fetch is an advanced form for the old but not outdated way (XMLHttpRequest).

Parameters/Properties :

  • URL: fetch takes the URL of the request

  • BODY: You can specify the data to send to the server in the body property

  • Request Method: Fetch can take all the request methods such as the get, post, put, delete.

CODELAB Worthy of note that fetch gives us a promise of which we should attach a .then method , If you have not heard of promises I suggest you read about it

Above is the first statement you ought to write to declare a fetch request. While the URL takes the URL of your database. During this CodeLab we'd be fetching quote from quotes.rest using this url (https://quotes.rest/qod.json?category=inspire), Notice this is a get request.

fetch("https://quotes.rest/qod.json?category=inspire")
.then(response=>response.text())
.then((data)=>{
  console.log(data);
});

CODE EXPLAINED

fetch("https://quotes.rest/qod.json?category=inspire") like I said returns a promise and we attach a .then method to fetch the request in text format with (response.text()) we can use response.json(). Then we attach a promise to the response with (.then(data)) which we then console. You can try out the code and play with it.

Using Post Request

We assume an anonymous server-side URL which accepts a post request (username)

fetch(url,{
method: 'POST',
body: JSON.stringify({"username":"username"});
})
.then(response=>response.text())
.then((data)=>{
console.log(data):
});

Yoo, Guess what ? you already now fetch request so you can now use fetch request for all your async request. Ohh, You have a question, Do not hesitate to drop your questions... :)

A new day, Another oppurtunity to be a World Class Software developer

More from this blog

C

Cracked Chefs by Oluwaferanmi Adeniji

19 posts

Battle-tested Coding patterns, Javascript wizardry, System Design, Product Engineering and Management, and architectural secrets.

What the heck is Fetch Request </>