admin管理员组

文章数量:1394611

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

  ponentDidMount() {
    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;

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

  ponentDidMount() {
    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;
Share Improve this question asked Jan 22, 2019 at 3:50 David SandersDavid Sanders 1311 gold badge3 silver badges16 bronze badges 3
  • MDN has a good example of this in their docs actually. – Andrew Dibble Commented Jan 22, 2019 at 3:53
  • What’s the end point for post request? – Hemadri Dasari Commented Jan 22, 2019 at 4:07
  • 'http://localhost:5000/api/listitems' – David Sanders Commented Jan 22, 2019 at 4:13
Add a ment  | 

1 Answer 1

Reset to default 4

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

本文标签: javascriptHow to Post data to database using Fetch API in ReactjsStack Overflow