Introduction

This tutorial will show you how to make an HTTP request using the fetch API

Introduction

HTTP requests are asynchronous in nature because data requested over the internet isn’t immediately available upon the request until we get a response from the server, hence we always use Promises or async/await

1. GET Requests

A get requests “reads” resource from the HTTP server and the server completes the request by sending a response. fetch is a Browser API that can be used to make HTTP requests:

// with ES6 Promises:
fectch(url)
  .then(res => res.json()) // convert response into a JavaScript Object
  .then(data => console.log(data)) // use the Object converted

async/await provides a cleaner way compared to the above:

const main = async() => {
  try {
    const res = await fetch(url)
    const data = await res.json()
    return data
  } catch(err) {
   console.log(err) 
  }
}

main()

2. POST Requests

A POST request is a request that usually leads to updating a resource on the HTTP server such as saving a file to disk, updating a Table entry in a Database.

To make a POST request using fetch, pass an object containing the options as a second argument like this: fetch(URL, options).

const postData = () => {
  let options = {
    method: 'POST',
    headers: {
      // define all headers required for the request here- such as Access-Control-Allow-Origin, Content-Type, Authorization
    },
    body: {} // body of request
  }
  const res = await fetch(url, options)
  const data = await res.json()
}

Since POST requests lead to modification of a resource, the Authorization header field needs to be always set in most cases.

const saveEpisode = async() => {
  let token = 'a-dumy-token'
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}` // API KEY etc.
    },
    body: JSON.stringify({name: 'Vat Of Acid', season: 'SN4', episode: 12})
  }

  // send the data
  const res = await fetch('http://api.foreverrickandmorty.com', options)
  const data = await res.json() // convert response into a JavaScript Object
  // use data from the response here
}

fetch API comes in handy for making requests as a much preferable way compared to XHttpRequest. See https://www.w3schools.com/xml/xml_http.asp

Summary

fetch API provides an intuitive way of making GET and POST requests on the browser.