How to make a rest post call from ReactJS code?

前端 未结 9 1916
一生所求
一生所求 2020-12-02 05:28

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 h

相关标签:
9条回答
  • 2020-12-02 06:09

    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);   
        });
      }
    
    0 讨论(0)
  • 2020-12-02 06:13

    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);
    });  
    
    0 讨论(0)
  • 2020-12-02 06:16

    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);
      });
    
    0 讨论(0)
提交回复
热议问题