How to make a rest post call from ReactJS code?

ReactjsReactjs FluxReactjs Native

Reactjs Problem Overview


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.

Reactjs Solutions


Solution 1 - Reactjs

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.)

Solution 2 - Reactjs

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

Solution 3 - Reactjs

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

Solution 4 - Reactjs

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

Solution 5 - Reactjs

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) {
           ...
        }
    }
    ...
}

Solution 6 - Reactjs

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

Solution 7 - Reactjs

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

Solution 8 - Reactjs

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

Solution 9 - Reactjs

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;

Solution 10 - Reactjs

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 (

submit(e)}>
handel(e) } id="name" value={state.name} placeholder="name" type="text" > handel(e) } id="iduser" value={state.iduser} placeholder="iduser" type="text" >

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

); }

Solution 11 - Reactjs

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDivyaView Question on Stackoverflow
Solution 1 - ReactjsMichael LortonView Answer on Stackoverflow
Solution 2 - ReactjsamannView Answer on Stackoverflow
Solution 3 - ReactjsVivek DoshiView Answer on Stackoverflow
Solution 4 - ReactjsChandrakant ThakkarView Answer on Stackoverflow
Solution 5 - ReactjsKevin Le - KhnleView Answer on Stackoverflow
Solution 6 - ReactjsMr FunView Answer on Stackoverflow
Solution 7 - Reactjsuser3603575View Answer on Stackoverflow
Solution 8 - Reactjsshailesh gavatheView Answer on Stackoverflow
Solution 9 - ReactjsKumarView Answer on Stackoverflow
Solution 10 - ReactjsRakesh yash k sView Answer on Stackoverflow
Solution 11 - ReactjsSanyam AgrawalView Answer on Stackoverflow