147

I am new to ReactJS and UI and I wanted to know how to make a simple REST based POST call from ReactJS code.

If there is any example present it would be really helpful.

Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
Divya
  • 1,577
  • 3
  • 12
  • 8

12 Answers12

246

Straight from the React Native docs:

fetch('https://mywebsite.example/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.)

Also see docs for ReactJS AJAX FAQs if not using React Native.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
  • Thanks for the example :) but now I am getting another error 'cant find variable fetch'.Also I am totally new to React JS so I am not sure whether this is the correct way to do it var APP = React.createClass ({ render() { return ( fetch('http://localhost:8080/api/ui/start', { method: 'POST', body: JSON.stringify({ Id: '112', User: 'xyz', }) }) ); } }); – Divya Jul 21 '16 at 18:05
  • 6
    You have to [install it and import it](https://github.com/github/fetch). Don't forget, the `fetch()` function doesn't return the _data_, it just returns a [promise](https://www.promisejs.org/). – Michael Lorton Jul 21 '16 at 19:57
  • 1
    haha @Divya, I was just about to make the same comment before reading yours. Not sure whether or not to put it in React.createClass. Also, could we please have a link to the react docs? I tried to search their site (https://facebook.github.io/react/docs/hello-world.html) unsuccessfully. – Tyler L Jan 01 '17 at 05:36
  • 1
    Can we please modify the original answer to include the import? – Tyler L Jan 01 '17 at 15:46
  • @user6582640 -- the import actually depends on exactly where you get `fetch()`. – Michael Lorton Jan 01 '17 at 23:03
  • Life saver #MalvloioYouTheRealMVP I wasn't using JSON.stringify #5hoursLater – GregarityNow Apr 06 '17 at 18:13
  • 7
    IMO, @amann has a [better answer below](https://stackoverflow.com/a/38512250/1003959). This answer implies `fetch` is built into React, which it is not, and there is no link to the docs referenced. `fetch` is (at time of writing) [an experimental Promise-based API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). For browser-compatibility, you'll need [a babel polyfill](https://github.com/github/fetch). – chris May 22 '17 at 22:04
  • 2
    Note, that this is from the React Native docs, not the React JS docs, but you may use Fetch_API in React JS as well. https://facebook.github.io/react-native/docs/network.html – Pål Brattberg Oct 20 '17 at 07:29
29

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(…)

amann
  • 5,449
  • 4
  • 38
  • 46
  • 7
    To me, this is the best answer, because React doesn't have anything built in. You either have to import `fetch` or `superagent` or `jQuery` or `axios` or something else that is not part of "vanilla React" in order to do anything other than what is posted above. – vapcguy Mar 14 '18 at 19:53
  • It looks like if you're using flask, it works well to do `JSON.stringify({"key": "val"})` and then on the flask side do `request.get_json()` – Pro Q Feb 21 '19 at 08:21
  • Yep, if you're posting JSON, you have to `JSON.stringify` it first. – amann Feb 21 '19 at 15:17
23

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);
  });
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
9

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

As of 2018 and beyond, you have a more modern option which is to incorporate async/await in your ReactJS application. A promise-based HTTP client library such as axios can be used. The sample code is given below:

import axios from 'axios';
...
class Login extends Component {
    constructor(props, context) {
        super(props, context);
        this.onLogin = this.onLogin.bind(this);
        ...
    }
    async onLogin() {
        const { email, password } = this.state;
        try {
           const response = await axios.post('/login', { email, password });
           console.log(response);
        } catch (err) {
           ...
        }
    }
    ...
}
Kevin Le - Khnle
  • 10,579
  • 11
  • 54
  • 80
5

I think this way also a normal way. But sorry, I can't describe in English ((

    submitHandler = e => {
    e.preventDefault()
    console.log(this.state)
    fetch('http://localhost:5000/questions',{
        method: 'POST',
        headers: {
            Accept: 'application/json',
                    'Content-Type': 'application/json',
        },
        body: JSON.stringify(this.state)
    }).then(response => {
            console.log(response)
        })
        .catch(error =>{
            console.log(error)
        })
    
}

https://googlechrome.github.io/samples/fetch-api/fetch-post.html

fetch('url/questions',{ method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(this.state) }).then(response => { console.log(response) }) .catch(error =>{ console.log(error) })

Mr Fun
  • 331
  • 3
  • 11
2

Here is a the list of ajax libraries comparison based on the features and support. I prefer to use fetch for only client side development or isomorphic-fetch for using in both client side and server side development.

For more information on isomorphic-fetch vs fetch

Community
  • 1
  • 1
user3603575
  • 89
  • 1
  • 8
0

Here is a util function modified (another post on stack) for get and post both. Make Util.js file.

let cachedData = null;
let cachedPostData = null;

const postServiceData = (url, params) => {
    console.log('cache status' + cachedPostData );
    if (cachedPostData === null) {
        console.log('post-data: requesting data');
        return fetch(url, {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(params)
          })
        .then(response => {
            cachedPostData = response.json();
            return cachedPostData;
        });
    } else {
        console.log('post-data: returning cachedPostData data');
        return Promise.resolve(cachedPostData);
    }
}

const getServiceData = (url) => {
    console.log('cache status' + cachedData );
    if (cachedData === null) {
        console.log('get-data: requesting data');
        return fetch(url, {})
        .then(response => {
            cachedData = response.json();
            return cachedData;
        });
    } else {
        console.log('get-data: returning cached data');
        return Promise.resolve(cachedData);
    }
};

export  { getServiceData, postServiceData };

Usage like below in another component

import { getServiceData, postServiceData } from './../Utils/Util';

constructor(props) {
    super(props)
    this.state = {
      datastore : []
    }
  }

componentDidMount = () => {  
    let posturl = 'yoururl'; 
    let getdataString = { name: "xys", date:"today"};  
    postServiceData(posturl, getdataString)
      .then(items => { 
        this.setState({ datastore: items }) 
      console.log(items);   
    });
  }
shailesh gavathe
  • 341
  • 3
  • 10
0

Here is the simple method to define and call post APIs in reactjs. Install axios using command npm install axios and call post req method wherever you want, it will return array that contains 100 elements.

// Define post_req() Method in authAction.js

import axios from 'axios';

const post_req = (data) => {
return new Promise((resolve, reject) => {
const url = 'https://jsonplaceholder.typicode.com/posts'
const header = {
    "Access-Control-Allow-Origin": "*",
    "Content-Type: application/json"
}
axios({
    method: 'post',
    url: url,
    data: data,
    headers: header
 });
 .then((res)=>{resolve(res);})
 .catch((err)=>{reject(err);})
 })
}

// Calling post_req() Method in react component 
import React, { Component } from 'react';
import { post_req } from 'path of file authAction.js'

class MyReactComponent extends Component {
constructor(props) {
super(props);
this.state = {
 myList:[]
 };
}
componentDidMount() {
let data = {
 .......
 } 
 this.props.post_req(data)
 .then((resp)=>{this.setState({myList:resp.data})})
 .catch((err)=>{console.log('here is my err',err)})
}
render() {
return (
  <div>
    ....
  </div)
 }
}
export default MyReactComponent;
Kumar
  • 436
  • 1
  • 4
  • 16
0

import React ,{useState}from 'react'; import Axios from 'axios';

export default function Formlp() {

const url ="";

const [state, setstate] = useState({
    name:"",
    iduser:""
})

function handel(e){

    const newdata={...state}
    newdata[e.target.id]=e.target.value
    setstate(newdata);
}

function submit(e)
{
    e.preventDefault();

  //  Axios.post(url,{name:state.name,iduser:state.iduser}).then( res=>{console.log(res)});

  console.log(state)

}

return ( <div onSubmit={ (e)=> submit(e)}> <input onChange={ (e)=>handel(e) } id="name" value={state.name} placeholder="name" type="text" > <input onChange={ (e)=>handel(e) } id="iduser" value={state.iduser} placeholder="iduser" type="text" >

        <button>submit</button>
        </form>
    </div>

); }

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 17 '21 at 11:36
0

Here is a quick example for v18+ while handling form data and creating a POST request with the data.

async function handleOrderSubmit(event){
  event.preventDefault()

  try{
    const formData= {name: event.target.name.value, email: event.target.email.value, message: event.target.name.message}
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
    };
    const response = await fetch('https://www.example.com/form', requestOptions);
    const data = await response.json();
    navigate("/form-response", { state: {data: data, status: true} })
  }
  catch(error){
    navigate("/form-response", { state: {status: false} })
  }
}

Note 1: Using status on '/form-response' page, you can customise what to show user. For true, you can show a different section and for false a different one.

Note 2: If the status is successful, you can access data on the next page also and customise it according to user information.

Note 3: event.preventDefault() is important to avoid page reloading.

Shubham Sarda
  • 539
  • 5
  • 10
-6

Here is an example: https://jsfiddle.net/69z2wepo/9888/

$.ajax({
    type: 'POST',
    url: '/some/url',
    data: data
  })
  .done(function(result) {
    this.clearForm();
    this.setState({result:result});   
  }.bind(this)
  .fail(function(jqXhr) {
    console.log('failed to register');
  });

It used jquery.ajax method but you can easily replace it with AJAX based libs like axios, superagent or fetch.

T J
  • 42,762
  • 13
  • 83
  • 138
  • Thanks a lot for the example :) . I also wanted to understand if my service expects JSON format data.Then what changes would be required ? Any sort of information would be really helpful. So when I am using the curl command to hit the endpoint its like curl -v -X POST http://localhost:8080/myapi/ui/start -d '{"Id":"112","User":"xyz"}' so how can I call such a service. – Divya Jul 21 '16 at 17:54
  • create a variable called data with `'{"Id":"112","User":"xyz"}'` and change the URL to localhost:8080/myapi/ui/start , thats about it , once the XHR call is successful you will land on in the done method and you will have access to you data via the result property. – Sanyam Agrawal Jul 22 '16 at 01:36