Using Fetch API to POST JSON Data in JavaScript
Introduction
In web development, we often need to communicate with servers to send or receive data. This is typically done via HTTP requests, and one of the most common types of requests is the POST request. In this Byte, we're going to explore how to use the Fetch API to send POST requests with JSON data from our JavaScript applications.
The Fetch API
The Fetch API is a modern, promise-based API that makes it easy to make asynchronous HTTP requests from the browser or Node.js. It's built into most modern browsers and replaces the older, callback-based XMLHttpRequest.
Here's a basic example of how to use the Fetch API to send a GET request:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
The fetch()
call returns a Promise that resolves to the Response
object which represents the response to the request. The response.json()
method also returns a Promise that resolves with the result of parsing the body text as JSON.
How to Post JSON Data with Fetch API
To send a POST request with JSON data using Fetch, we need to pass an options
object as the second argument to fetch()
. This object includes properties like method
, headers
, and body
.
Here's how we can do it:
const url = 'https://api.example.com/data';
const data = { username: 'example' };
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
console.error('Error:', error);
});
Using this code, we're sending a POST request to the specified URL with a JSON body. The JSON.stringify()
method is used to convert a JavaScript object or value to a JSON string.
Handling Errors in Fetch API
One thing to note about the Fetch API is that it doesn't reject the Promise on HTTP error status, even if the response is an HTTP 404 or 500. Instead, it will only reject on network failure or if anything prevented the request from completing.
Personally, I prefer this style as it's easier to work with than handling these errors in a catch
method. For example, retrying a request that returned HTTP 500 is eaiser to do when it doesn't throw an error. It also gives us more control over how we want to handle errors.
To actually handle HTTP errors, we need to check if the response.ok
property is true
, which indicates that the response was successful (status is in the range 200-299). If response.ok
is false
, we can either choose to throw an error or handle it right there.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('HTTP error ' + response.status);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
If the HTTP status code is not in the range 200-299, an error will be thrown, and the catch block can then handle it.
Comparing Fetch to Axios
If you're used to using another library, you might be wondering how Fetch compares to other popular HTTP clients like Axios. Both Fetch and Axios can be used to send HTTP requests from JavaScript, but there are a few key differences between the two.
Fetch is now built into most modern browsers, which means you can use it without installing any additional libraries. It returns Promises natively and is generally simpler and more straightforward to use. However, one downside is it doesn't support request cancellation, and error handling doesn't work the way many developers expect it to, as it only rejects a Promise on network failure, not on HTTP error status.
On the other hand, Axios needs to be installed as a separate library, but it provides a wider range of features. It supports request cancellation, automatic transformation of JSON data, and provides a way to set a response timeout. It also rejects a Promise on HTTP error status, which you may prefer over Fetch's way of doing it.
Conclusion
In this short Byte, we learned how to use the Fetch API to POST JSON data, and we compared Fetch to Axios. Fetch is a powerful tool built into modern browsers that allows us to send HTTP requests directly from JavaScript. While it may lack some of the advanced features of Axios, it's a convenient and straightforward solution for many use cases.