Fetch JavaScript

Okechukwu Uneze
2 min readFeb 5, 2022

JavaScript can send network requests to the server and load new information whenever it’s needed.

For example, we can use a network request to:

  • Submit an order,
  • Load user information,
  • Receive latest updates from the server,
  • …etc.

The fetch() method is modern and versatile, so we’ll start with it. It’s not supported by old browsers (can be polyfilled), but very well supported among the modern ones.

GET requests

The basic syntax is:let promise = await fetch(url, [options]);
let json = await response.json();
  • url: the URL to access.
  • options: optional parameters: method, headers, Body, etc.

Request headers

To set a request header in fetch, we can use the headers option. It has an object with outgoing headers, like this:

let response = fetch(protectedUrl, {
headers: {
Authentication: 'secret'
}
});

POST requests, PUT requests

To make a POST/PUT request, or a request with another method, we need to use fetch options:

  • method – HTTP-method, e.g. POST/PUT,
  • body – the request body

Example:

//Post Request
let data = { name: 'Okechukwu', surname: 'Uneze' };

--

--