如何从ReactJS代码进行休息后调用?

Div*_*vya 115 reactjs reactjs-flux reactjs-native

我是reactJS和UI的新手,我想知道如何从reactJS代码中进行简单的基于休息的POST调用.

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

谢谢.

Mal*_*lio 192

直接来自React文档:

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

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

  • IMO,@ amann有一个[下面更好的答案](/sf/answers/2695857531/).这个答案意味着`fetch`是内置在React中的,它不是,并且没有链接到引用的文档.`fetch`是(在撰写本文时)[基于Promise的实验性API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).对于浏览器兼容性,您需要[babel polyfill](https://github.com/github/fetch). (5认同)
  • 您必须[安装并导入](https://github.com/github/fetch).不要忘记,`fetch()`函数不返回_data_,它只返回一个[promise](https://www.promisejs.org/). (4认同)
  • 请注意,这是来自 React Native 文档,而不是 React JS 文档,但您也可以在 React JS 中使用 Fetch_API。https://facebook.github.io/react-native/docs/network.html (2认同)

ama*_*ann 22

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);
Run Code Online (Sandbox Code Playgroud)

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

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

  • 对我来说,这是最好的答案,因为React没有任何内置的东西.你要么必须导入`fetch`或`superagent`或`jQuery`或`axios`或其他不属于"vanilla React"的东西"为了做除上述内容之外的任何事情. (4认同)

Viv*_*shi 15

另一个最近流行的套餐是:axios

安装: npm install axios --save

基于简单承诺的请求


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


Cha*_*kar 9

你可以安装superagent

npm install superagent --save
Run Code Online (Sandbox Code Playgroud)

然后对服务器进行post 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);
});  
Run Code Online (Sandbox Code Playgroud)


Kev*_*nle 5

从2018年开始,您还有一个更现代的选择是将异步/等待合并到ReactJS应用程序中。可以使用基于承诺的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) {
           ...
        }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)


Mr *_*Fun 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)
        })
    
}
Run Code Online (Sandbox Code Playgroud)

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

fetch('url / questions',{方法:'POST',标头:{接受:'application / json','Content-Type':'application / json',},正文:JSON.stringify(this.state) })。then(response => {console.log(response)}).catch(error => {console.log(error)})


小智 -6

这是一个示例: 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');
  });
Run Code Online (Sandbox Code Playgroud)

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