Learn to Code via Tutorials on Repl.it!

← Back to all posts
JS Fetch API Tutorial 📜
h
PowerCoder (690)

Fetch, the modern way to make HTTP requests in Javascript. There are many ways to make your HTTP requests like using XHR however, some of them aren't as simple as fetch. Today, we'll be discussing how to use fetch for AJAX/HTTP requests.

Overview:

fetch(reqLink, options*:optional*)

The options argument should be an object/JSON data-type. The reqLink is where you put your request link. The reqLink should be a string.

When you use the fetch function what should be returned is a JS promise.
This is what a promise is: developer.mozilla.org
(JSONplaceholder is an arbituary fake REST API that I chose.) You can check them out here
I'm going to be using an arrow function in these examples which are another way to declare functions
For more information on arrow functions go here

GET request example 📜:

//JSON placeholder is a simple placeholder REST API that returns JSON
fetch("https://jsonplaceholder.typicode.com/todos/1")
    .then(response=> {
        //response.json() turns the response objects body into JSON 
        //response.json() returns a JS promise
        //Use response.text() to turn your response object to text
        return response.json()
    })
    .then(data=> {
        //We have successfully made a GET request!
        //Log the data to the console:
        console.log(data);
    })

POST request example 📜:

fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    body: JSON.stringify({
      title: 'foo',
      body: 'bar',
      userId: 1
    }),
    headers: {
      "Content-type": "application/json"
    }
  })
  .then(response => response.json())
  .then(json => console.log(json))

The body property is used to insert data through the POST request.

Helpful Tips 😁:

  • To make a GET request, you don't need anything in the options argument.
  • To handle your JS promises in a cleaner way, use an asynchronous function

Thanks for reading this far👍
Please consider upvoting this post, it really helps me out 😉
Feel free to give me any suggestions😄