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

懵懂的女人 提交于 2021-02-10 06:10:32

问题


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.

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

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;

回答1:


You can do something like below

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


来源:https://stackoverflow.com/questions/54300992/how-to-post-data-to-database-using-fetch-api-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!