Different Ways to Make a POST Request in React
-
Use
fetch()
to Make aPOST
Request in React -
Use
axios
to Make aPOST
Request in React -
Use Plain JavaScript to Make a
POST
Request in React
Working with an API is essential when building complex web applications in React. Most of the time, applications make get
requests to read the data from an API.
Sometimes it’s necessary to make post
requests, which update the data on the API. This article explores how to make post
requests in React.
There are multiple ways to interact with API in React. In this article, we want to discuss the most common ways to do so.
React library does not offer one specific solution for making REST
calls. Any AJAX library compatible with JavaScript can be used in React as well.
Use fetch()
to Make a POST
Request in React
The Fetch
API is the most common and easiest way to make REST
calls in JavaScript. Reading the value from an API URL is as easy as calling fetch()
with the API URL.
Making POST
requests is slightly more complicated but still fairly easy. Let’s examine one example of a simple fetch
request.
fetch('https://samplewebsite.com/API/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
parameterOne: 'something',
parameterTwo: 'somethingElse'
})
});
This is an example of a simple POST
request made with fetch()
. Read the official documentation to learn more about the Fetch
API, like the list of potential parameters.
Use axios
to Make a POST
Request in React
This is another popular package for making requests in React. It is not natively included in JavaScript, so you’ll have to install it to send requests.
To install the axios
package, run the following command in npm
.
npm install axios --save
Once installed, you can make POST
requests that look even simpler than the Fetch
API.
axios
.post('/endpoint', {
name: 'John Doe',
})
.then(function(response) {
return response;
})
.catch(function(error) {
return error;
});
This is a basic example of making POST
requests with axios
.
Use Plain JavaScript to Make a POST
Request in React
In JavaScript, the traditional way to send any request to an API is using the XMLHttpRequest()
interface. You can create an instance of this object and store it in the variable.
var req = new XMLHttpRequest();
req.open('POST', '/endpoint', true);
req.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
req.send(data);
It might look less straightforward, but it accomplishes the same result as the POST
calls made with fetch
and axios
.
Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.
LinkedIn