Fetch it!

Beza Sirak
3 min readApr 30, 2020

What is a Fetch request?

fetch() provides an easy, fast, and logical way to asynchronously fetch across the network. Previously the same function was done using XMLHttpRequest. Using fetch(), you can get, post, put, patch, and delete data from API with the proper credentials.

Fetch Differs from jQuery.ajax()

Ajax stands for Asynchronous JavaScript and XML and allows us to create fast web pages that do not require to reload the whole page.

There are three main ways that fetch() differed from jQuery.ajax()

  1. When requesting a fetch(), the response promise doesn’t reject HTTP error status even if the response is an HTTP 404 or 500. Instead, it will change the status Ok to false and resolves it. It would only reject on network failure or anything that prevents it from completing the request.
  2. fetch()won’t receive cross-site cookies, meaning it is impossible to make a cross-site session using fetch. Cross-site cooking is a type of browser exploit where an attacker can set a cookie for a browser into a cookie domain of another site, which means the attacker can move data in between different sites. When using fetch() such activities are not allowed. Set-Cookie headers from other sites are simply ignored.
  3. fetch() also will not send cookies unless you change the default credentials init Option to include from sam-origin.

Basic Fetch Request

The fetch() takes in a URL path to which it accesses an API. The URL is also known as the endpoint. The fetch call returns a response. At this stage, it is still an HTTP response, not a JSON. To get the JSON body from the HTTP, we use the json() method. Once we have the JSON file, we can manipulate the data. For this basic request, we are loving it on the console to see the data.

Fetch Request Can Take a Second Parameter

fetch() request can optionally accept a second parameter that allows you to change the default setting. The ones with the stars are the default settings.

Same OriginCredtional

Credentials are set to ‘same-origin’ by default in a fetch request. This means you only want to send credentials as long as the request URL and the calling script is in the same domain. Example, if your working on localhost, your traditional can only be sent to the request is on localhost: then calling script should c

Include Credential

Changing the credentials to include lets the browser to send a request with credentials even if the origin is not the same as the request.

Omit Credential

If you don’t want to send any credentials when requesting a fetch, you can change the credential to “omit”.

Resources

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

--

--

Beza Sirak

I am a software developer and a certified scrum master whose passion is to solve business problems using technology.