且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在React.js Web应用程序中将数据发送到数据库

更新时间:2023-01-01 16:38:28

您需要一台服务器来处理来自的请求您的React应用程序并相应地更新数据库。 单向将使用NodeJS,Express和 node-mysql 作为服务器:

You will need a server that handles requests from your React app and updates the database accordingly. One way would be to use NodeJS, Express and node-mysql as a server:

var mysql = require('mysql');
var express = require('express');
var app = express();

// Set up connection to database.
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'me',
  password: 'secret',
  database: 'my_db',
});

// Connect to database.
// connection.connect();

// Listen to POST requests to /users.
app.post('/users', function(req, res) {
  // Get sent data.
  var user = req.body;
  // Do a MySQL query.
  var query = connection.query('INSERT INTO users SET ?', user, function(err, result) {
    // Neat!
  });
  res.end('Success');
});

app.listen(3000, function() {
  console.log('Example app listening on port 3000!');
});

然后你可以使用 fetch 在一个React组件中向服务器发出POST请求,有点像这样:

Then you can use fetch within a React component to do a POST request to the server, somewhat like this:

class Example extends React.Component {
  constructor() {
    super();
    this.state = { user: {} };
    this.onSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(e) {
    e.preventDefault();
    var self = this;
    // On submit of the form, send a POST request with the data to the server.
    fetch('/users', { 
        method: 'POST',
        data: {
          name: self.refs.name,
          job: self.refs.job
        }
      })
      .then(function(response) {
        return response.json()
      }).then(function(body) {
        console.log(body);
      });
  }
  render() {
    return (
      <form onSubmit={this.onSubmit}>
        <input type="text" placeholder="Name" ref="name"/>
        <input type="text" placeholder="Job" ref="job"/>
        <input type="submit" />
      </form>
    );
  }
}

请记住,这只是无限的方式之一实现这一目标。

Keep in mind that this is only one of infinite ways to achieve this.