Sitemap

Fetch(problems, eh!)

2 min readMay 14, 2023

--

In modern world of web development, it is very common to see web applications interact with server without having to reload the entire page. One way to do this in javascript is by using fetch() method. It is a built-in method in javascript that allows you to make requests and retrieve data from the server. It returns a Promise that resolves to the response from the server.

Get Harpreet Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

Here’s a basic example of how to use the fetch() method to make a GET request to an API and retrieve data:

                  fetch('https://randomapiaddress')
.then(response => response.json())
.then(quote => console.log(quote))
.catch(error => console.error(error))

In the above example, we use the fetch() method to make a GET request to an API. We then chained two .then() methods to the Promise returned by fetch(). The first .then() method will convert the response from the server to JSON format using the .json() method. The second .then() method will log the data to the console. We also added a .catch() method to handle any errors that might occur during the request.

We can also use .fetch() method to make other types of requests such as POST, PATCH and DELETE by passing additional options to the method.

fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'xyz',
email: 'xyz@example.com'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

In above example, we used a fetch() method to make a POST request to the api. We pass an object as the second argument to fetch() that contains options for the request. We specify the HTTP method and set the Content-Type header to ‘application/json’ and pass a JSON object as the request body.

--

--