Using the Fetch API

With the Fetch API, you can make web requests. The idea of the Fetch API is similar to traditional XMLHttpRequest, but the Fetch API also supports promises that makes it more straightforward to use.

The Fetch API provides a fetch() method that has one mandatory argument, which is the path of the resource you are calling. In the case of a web request, it will be the URL of the service. For a simple GET method call, which returns a JSON response, the syntax is the following. The fetch() method returns a promise that contains the response. You can use the json() method to parse the JSON body from the response:

fetch('http://someapi.com')
.then(response => response.json())
.then(result => console.log(result));
.catch(error => console.error(error))

To use another HTTP method, such as POST, you can define it in the second argument of the fetch method. The second argument is the object where you can define multiple request settings. The following source code makes the request using the POST method:

fetch('http://someapi.com', {method: 'POST'})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error(error));

You can also add headers inside the second argument. The following fetch call contains the 'Content-Type' : 'application/json' header:

fetch('http://someapi.com', 
{
method: 'POST',
headers:{'Content-Type': 'application/json'}
}
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error(error));

If you have to send JSON-encoded data inside the request body, the syntax is the following:

fetch('http://someapi.com', 
{
method: 'POST',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify(data)
}
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error(error));

You can also use other libraries for the network calls. One very popular library is axios (https://github.com/axios/axios), which you can install to your React app with npm. axios has some benefits, such as automatic transform for JSON data. The following code shows the example call with axios:

axios.get('http://someapi.com')
.then(response => console.log(response))
.catch(error => console.log(error));

axios has its own call methods for the different HTTP methods. For example, if you want to make a DELETE request, axios provides the axios.delete method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.206.25