如何从ReactJS代码中发出REST POST调用?

148

我刚接触ReactJS和UI,想知道如何从ReactJS代码中进行一个简单的基于REST的POST调用。

如果有任何示例现成的话,那将非常有帮助。


8
请选出对您有帮助的答案。 - Socrates
12个回答

248

直接引用自React Native文档:

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

(这是发布JSON,但你也可以做例如分段表格等其他事情。)

如果不使用React Native,请参阅ReactJS AJAX FAQs文档。


6
你需要安装并导入它。记住,fetch()函数不会返回数据,它只返回一个promise - Michael Lorton
1
哈哈,@Divya,我正要在看到你的评论之前发表同样的评论。不确定是否应该将其放在React.createClass中。另外,我们能否请提供React文档的链接?我试图在他们的网站上搜索(https://facebook.github.io/react/docs/hello-world.html),但没有成功。 - Tyler L
1
我们能否修改原始答案以包含导入(import)? - Tyler L
7
IMO,@amann在下面给出了更好的答案。这个答案暗示了fetch已经内置于React中,但实际上并没有,并且没有提供参考文档的链接。在撰写本文时,fetch一种实验性的基于Promise的API。为了实现浏览器兼容性,您需要使用babel polyfill - chris
2
请注意,这是来自React Native文档而不是React JS文档,但您也可以在React JS中使用Fetch_API。https://facebook.github.io/react-native/docs/network.html - Pål Brattberg
显示剩余3条评论

29

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


7
对我来说,这是最好的答案,因为React本身并没有内置任何东西。除了以上所述的基本内容之外,如果你想要做其他事情,你需要导入fetchsuperagentjQueryaxios或其他不属于"vanilla React"的东西。 - vapcguy
看起来如果你正在使用Flask,那么做JSON.stringify({"key": "val"})是有效的,然后在Flask端执行request.get_json() - Pro Q
是的,如果你要发布JSON,你必须先使用JSON.stringify - amann

23

另一个最近流行的包是: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);
  });

9
您可以安装SuperAgent。
npm install superagent --save

然后进行向服务器发起POST请求的操作。
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

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

由于某些原因,Node.js无法解释await- SyntaxError:await是保留字(33:19) - prayagupa
@prayagupd,你在使用哪个版本的Node? - Kevin Le - Khnle

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发送POST请求:

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

2
这段文字的翻译如下:

这是一个基于功能和支持的 Ajax 库比较列表,在这里可以找到。我更喜欢只用于客户端开发的 fetch 或者既可以在客户端又可以在服务器端使用的 isomorphic-fetch

想要了解更多关于 isomorphic-fetch vs fetch 的信息,请点击链接。


0

这是一个快速示例,用于处理表单数据并使用该数据创建POST请求的v18+。

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

注意1:在“/form-response”页面上使用status,您可以自定义向用户显示什么。对于true,您可以显示不同的部分,对于false则显示另一个部分。

注意2:如果状态成功,您还可以在下一页上访问数据,并根据用户信息进行自定义。

注意3:event.preventDefault()很重要,以避免页面重新加载。


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)

}

返回 ( <div onSubmit={ (e)=> submit(e)}>

<input onChange={ (e)=>handel(e) } id="name" value={state.name} placeholder="姓名" type="text" > <input onChange={ (e)=>handel(e) } id="iduser" value={state.iduser} placeholder="用户ID" type="text" >

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

); }


目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

0

这里是在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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接