Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a rest post call from ReactJS code?

People also ask

How do you make a POST call in React JS?

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. Copy var req = new XMLHttpRequest(); req. open('POST', '/endpoint', true); req.

How do I POST a REST API in React JS?

Source code of the REST controller class is given below: import React from 'react'; class RestController extends React. Component { constructor(props) { super(props); this. state = {user: []}; } componentDidMount() { fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.

How do you POST data using fetch in React?

React Fetch POST examplestringify() on the object before passing it in the body of the request and set: "post" for method. "application/json" for the header Content-Type.


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);
  });

you can install superagent

npm install superagent --save

then for make post call to server

import request from "../../node_modules/superagent/superagent";

request
.post('http://localhost/userLogin')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ username: "username", password: "password" })
.end(function(err, res){
console.log(res.text);
});