如何在React.js中使用Fetch API将数据发布到数据库 [英] How to Post data to database using Fetch API in React.js

查看:38
本文介绍了如何在React.js中使用Fetch API将数据发布到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近学习了如何使用在MAMP服务器上运行的localhost mySQL数据库在快速服务器中设置简单的api.设置好之后,我学习了如何让React.js提取数据并显示它.现在,我想做相反的事情,并发布我在React.js中创建的表单中的数据.我想继续使用访存API来发布该数据.您可以在下面查看我的代码.

I have recently learned how to set up a simple api in my express server using a localhost mySQL database I have running on a MAMP server. After I set that up I learned how to have React.js fetch that data and display it. Now I want to do the reverse and post data from a form I created in React.js. I would like to continue using the fetch API to post that data. You can view my code below.

下面是我的api的快速服务器代码.

Below is my express server code for my api.

  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代码.

I have already set up the form and created the submit and onchange functions for the form. When I submit data it is just put in an alert. I would like to have that data posted to the database instead. IBelow is the React App.js code.

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

我的工作职位终点位于下面.

My working post endpoint is below.

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

这篇关于如何在React.js中使用Fetch API将数据发布到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆