How to make a rest post call from ReactJS code? How to make a rest post call from ReactJS code? reactjs reactjs

How to make a rest post call from ReactJS code?


Straight from the React docs:

fetch('https://mywebsite.com/endpoint/', {  method: 'POST',  headers: {    'Accept': 'application/json',    'Content-Type': 'application/json',  },  body: JSON.stringify({    firstParam: 'yourValue',    secondParam: 'yourOtherValue',  })})

(This is posting JSON, but you could also do, for example, multipart-form.)


React doesn't really have an opinion about how you make REST calls. Basically you can choose whatever kind of AJAX library you like for this task.

The easiest way with plain old JavaScript is probably something like this:

var request = new XMLHttpRequest();request.open('POST', '/my/url', true);request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');request.send(data);

In modern browsers you can also use fetch.

If you have more components that make REST calls it might make sense to put this kind of logic in a class that can be used across the components. E.g. RESTClient.post(…)


Another recently popular packages is : axios

Install : npm install axios --save

Simple Promise based requests


axios.post('/user', {    firstName: 'Fred',    lastName: 'Flintstone'  })  .then(function (response) {    console.log(response);  })  .catch(function (error) {    console.log(error);  });