如何使用 Fetch API in React.js 将数据 Post 写入数据库

How to Post data to database using Fetch API in React.js

我最近学会了如何使用我在 MAMP 服务器上 运行 的本地主机 mySQL 数据库在我的快速服务器中设置一个简单的 api。设置好之后,我学会了如何让 React.js 获取该数据并显示它。现在我想从我在 React.js 中创建的表单中执行反向和 post 数据。我想继续使用获取 API 到 post 的数据。您可以在下面查看我的代码。

下面是我的 api.

的快速服务器代码
  app.get('/api/listitems', (req, res) => {   
    connection.connect();  
    connection.query('SELECT * from list_items', (err,results,fields) => {
      res.send(results)
    })
    connection.end();
  });

我已经设置了表单并为表单创建了提交和 onchange 函数。当我提交数据时,它只是发出警报。我想将该数据 posted 到数据库中。下面是 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;

您可以执行如下操作

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

我的工作 post 端点如下。

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