【问题标题】:How to make a rest post call from ReactJS code?如何从 ReactJS 代码进行休息后调用?
【发布时间】:2016-11-25 10:11:12
【问题描述】:

我是 ReactJS 和 UI 的新手,我想知道如何从 ReactJS 代码进行简单的基于 REST 的 POST 调用。

如果有任何示例,那将非常有帮助。

【问题讨论】:

  • 能否请您选择对您有帮助的答案?

标签: reactjs reactjs-flux reactjs-native


【解决方案1】:

import React ,{useState}from 'react'; 从'axios'导入axios;

导出默认函数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)

}

返回 (

提交(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>

); }

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

这是在 reactjs 中定义和调用 post API 的简单方法。使用命令npm install axios 安装axios 并在任意位置调用post req 方法,它将返回包含100 个元素的数组。

// 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;

【讨论】:

    【解决方案3】:

    这是一个修改的 util 函数(堆栈上的另一个帖子),用于获取和发布两者。制作 Util.js 文件。

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

    在另一个组件中的用法如下所示

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

    【讨论】:

      【解决方案4】:

      直接来自React docs

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

      (这是发布 JSON,但您也可以发布,例如,multipart-form。)

      【讨论】:

      【解决方案5】:

      我认为这种方式也是一种正常的方式。但是抱歉,我无法用英语描述((

          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/问题',{ 方法:'POST', 标题:{ 接受:'应用程序/json', '内容类型':'应用程序/json', }, 正文:JSON.stringify(this.state) }).then(响应 => { 控制台日志(响应) }) .catch(错误 =>{ 控制台日志(错误) })

      【讨论】:

        【解决方案6】:

        从 2018 年及以后,您有一个更现代的选择,即在您的 ReactJS 应用程序中合并 async/await。可以使用基于 Promise 的 HTTP 客户端库,例如 axios。示例代码如下:

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

        【讨论】:

        • 出于某种原因,nodejs 确实解释了await - SyntaxError: await is a reserved word (33:19)
        • @prayagupd 你用的是什么版本的节点?
        【解决方案7】:

        另一个最近流行的包是:axios

        安装:npm install axios --save

        简单的基于 Promise 的请求


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

        【讨论】:

          【解决方案8】:

          你可以安装超级代理

          npm install superagent --save
          

          然后对服务器进行后调用

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

          【讨论】:

            【解决方案9】:

            React 对如何进行 REST 调用并没有真正的意见。基本上你可以为这个任务选择你喜欢的任何类型的 AJAX 库。

            使用普通的旧 JavaScript 最简单的方法可能是这样的:

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

            在现代浏览器中,您还可以使用fetch

            如果您有更多进行 REST 调用的组件,那么将这种逻辑放在一个可以跨组件使用的类中可能是有意义的。例如。 RESTClient.post(…)

            【讨论】:

            • 对我来说,这是最好的答案,因为 React 没有内置任何东西。你要么必须导入 fetchsuperagentjQueryaxios 或其他东西这不是“vanilla React”的一部分,以便做上面发布的内容之外的任何事情。
            • 看起来如果你正在使用烧瓶,它可以很好地执行JSON.stringify({"key": "val"}),然后在烧瓶一侧执行request.get_json()
            • 是的,如果你发布 JSON,你必须先JSON.stringify它。
            【解决方案10】:

            这里是一个例子: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');
              });
            

            它使用了jquery.ajax 方法,但您可以轻松地将其替换为基于 AJAX 的库,例如 axios、superagent 或 fetch。

            【讨论】:

            • 非常感谢这个例子:)。我还想了解我的服务是否需要 JSON 格式的数据。那么需要进行哪些更改?任何类型的信息都会非常有帮助。因此,当我使用 curl 命令访问端点时,它就像 curl -v -X POST localhost:8080/myapi/ui/start -d '{"Id":"112","User":"xyz"}' 那么我怎么能这样称呼一项服务。
            • 使用'{"Id":"112","User":"xyz"}' 创建一个名为 data 的变量并将 URL 更改为 localhost:8080/myapi/ui/start ,就是这样,一旦 XHR 调用成功,您将进入 done 方法您将可以通过 result 属性访问您的数据。
            【解决方案11】:

            Here 是一个基于特性和支持的ajax 库比较列表。 我更喜欢使用fetch 仅用于客户端开发或isomorphic-fetch 用于客户端和服务器端开发。

            欲了解更多关于isomorphic-fetch vs fetch的信息

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2016-09-08
              • 2019-07-06
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多