【发布时间】:2019-06-15 11:51:07
【问题描述】:
我最近学习了如何使用我在 MAMP 服务器上运行的 localhost mySQL 数据库在我的 express 服务器中设置一个简单的 api。设置好之后,我学会了如何让 React.js 获取数据并显示它。现在我想做相反的事情并从我在 React.js 中创建的表单中发布数据。我想继续使用 fetch API 来发布该数据。您可以在下面查看我的代码。
以下是我的 api 的快速服务器代码。
app.get('/api/listitems', (req, res) => {
connection.connect();
connection.query('SELECT * from list_items', (err,results,fields) => {
res.send(results)
})
connection.end();
});
我已经设置了表单并为表单创建了提交和 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;
【问题讨论】:
-
MDN 实际上有一个很好的例子in their docs。
-
post 请求的终点是什么?
-
'http://localhost:5000/api/listitems'
标签: javascript mysql reactjs rest fetch-api