Skip to content
← Back to Community
JS Fetch API Tutorial πŸ“œ
Profile icon

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.


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:
(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("") .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('', { 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πŸ˜„

Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon