我刚接触ReactJS和UI,想知道如何从ReactJS代码中进行一个简单的基于REST的POST调用。
如果有任何示例现成的话,那将非常有帮助。
我刚接触ReactJS和UI,想知道如何从ReactJS代码中进行一个简单的基于REST的POST调用。
如果有任何示例现成的话,那将非常有帮助。
直接引用自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文档。
fetch
已经内置于React中,但实际上并没有,并且没有提供参考文档的链接。在撰写本文时,fetch
是一种实验性的基于Promise的API。为了实现浏览器兼容性,您需要使用babel polyfill。 - chrisReact对于如何进行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(…)
fetch
、superagent
、jQuery
、axios
或其他不属于"vanilla React"的东西。 - vapcguyJSON.stringify({"key": "val"})
是有效的,然后在Flask端执行request.get_json()
。 - Pro QJSON.stringify
。 - amann另一个最近流行的包是: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);
});
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);
});
从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) {
...
}
}
...
}
await
- SyntaxError:await是保留字(33:19)
。 - prayagupa 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)
})
这是一个基于功能和支持的 Ajax 库比较列表,在这里可以找到。我更喜欢只用于客户端开发的 fetch 或者既可以在客户端又可以在服务器端使用的 isomorphic-fetch。
想要了解更多关于 isomorphic-fetch vs fetch 的信息,请点击链接。
这是一个快速示例,用于处理表单数据并使用该数据创建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()
很重要,以避免页面重新加载。
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)}>
<button>submit</button>
</form>
</div>
); }
这里是在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;