Javascript 如何在React.js中使用Fetch API将数据发布到数据库
我最近学习了如何使用在MAMP服务器上运行的localhost mySQL数据库在express服务器中设置一个简单的api。设置之后,我学习了如何让React.js获取并显示数据。现在,我想从我在React.js中创建的表单中反转并发布数据。我想继续使用fetchapi发布这些数据。您可以在下面查看我的代码 下面是我的api的express服务器代码Javascript 如何在React.js中使用Fetch API将数据发布到数据库,javascript,mysql,reactjs,rest,fetch-api,Javascript,Mysql,Reactjs,Rest,Fetch Api,我最近学习了如何使用在MAMP服务器上运行的localhost mySQL数据库在express服务器中设置一个简单的api。设置之后,我学习了如何让React.js获取并显示数据。现在,我想从我在React.js中创建的表单中反转并发布数据。我想继续使用fetchapi发布这些数据。您可以在下面查看我的代码 下面是我的api的express服务器代码 app.get('/api/listitems', (req, res) => { connection.connect
app.get('/api/listitems', (req, res) => {
connection.connect();
connection.query('SELECT * from list_items', (err,results,fields) => {
res.send(results)
})
connection.end();
});
我已经设置了表单,并为表单创建了submit和onchange函数。当我提交数据时,它只是放在一个警报中。我希望将这些数据发布到数据库中。IBelow是React App.js代码
import React, { Component } from 'react';
import './App.scss';
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
formvalue: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleData = () => {
fetch('http://localhost:5000/api/listitems')
.then(response => response.json())
.then(data => this.setState({ items: data }));
}
handleChange(event) {
this.setState({formvalue: event.target.value});
}
handleSubmit(event) {
alert('A list was submitted: ' + this.state.formvalue);
event.preventDefault();
}
componentDidMount() {
this.handleData();
}
render() {
var formStyle = {
marginTop: '20px'
};
return (
<div className="App">
<h1>Submit an Item</h1>
<form onSubmit={this.handleSubmit} style={formStyle}>
<label>
List Item:
<input type="text" value={this.state.formvalue} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
<h1>Grocery List</h1>
{this.state.items.map(
(item, i) =>
<p key={i}>{item.List_Group}: {item.Content}</p>
)}
<div>
</div>
</div>
);
}
}
export default App;
import React,{Component}来自'React';
导入“/App.scss”;
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
项目:[],
formvalue:“”
};
this.handleChange=this.handleChange.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
}
handleData=()=>{
取('http://localhost:5000/api/listitems')
.then(response=>response.json())
.then(data=>this.setState({items:data}));
}
手变(活动){
this.setState({formvalue:event.target.value});
}
handleSubmit(事件){
警报('已提交列表:'+this.state.formvalue);
event.preventDefault();
}
componentDidMount(){
这是handleData();
}
render(){
var formStyle={
玛金托普:“20px”
};
返回(
提交项目
清单项目:
杂货清单
{this.state.items.map(
(项目i)=>
{item.List_Group}:{item.Content}
)}
);
}
}
导出默认应用程序;
您可以执行以下操作
handleSubmit (event) {
//alert('A list was submitted: ' + this.state.formvalue);
event.preventDefault();
fetch('your post url here', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: this.state.id,
item: this.state.item,
itemType: this.state.itemType
})
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err);
}
我的工作岗位终点如下
app.post('/api/listitems', (req, res) => {
var postData = req.body;
connection.query('INSERT INTO list_items SET ?', postData, (error, results, fields) => {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
MDN实际上有一个很好的例子。post请求的终点是什么http://localhost:5000/api/listitems“这只是一个问题。我的mySQL表是这样设置的。行=>ID、项、项类型、日期。如果我的表单只有一个字段,让我们假设接受一个新的ItemType值。handleSubmit如何知道将这些数据放在何处。同样,我对通过网络获取数据非常陌生,我只是想更好地理解这一点。我认为state formValue是一个对象。您需要在handleSubmit中手动构造一个包含相关数据的对象,并将数据对象传递给fetch post Request主体中的JSON.stringify(数据)。请检查我的更新代码。您可以使用要发送到后端的所有值构造一个对象。我构造该对象并在状态中放置一些填充文本。当我运行handleSubmit函数时,它会在控制台中抛出这些错误。不知道这意味着什么<代码>邮政http://localhost:5000/api/listitems 404(未找到)App.js:49语法错误:JSON中位于位置0的意外标记<获取加载失败:POST“http://localhost:5000/api/listitems“是的,你在写。我的post端点设置不正确。现在它已经设置好了,一切都很好地发布到了数据库中。