在React.js Web应用程序中将数据发送到数据库 [英] Sending data to Database in React.js web application

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

问题描述

我正在创建一个Web应用程序,我很好奇如何将数据发送到MySQL数据库中。我有一个在用户按下按钮时调用的函数,我希望这个函数以某种方式将数据发送到MySQL服务器。有谁知道如何处理这个问题?我尝试了npm MySQL模块,但似乎连接不起作用,因为它是客户端。这样做还有其他办法吗?我需要一个想法让我开始。

I'm creating a web application and I'm curious how to send data to MySQL database in it. I have a function that is invoked when user presses button, I want this function somehow to send data to the MySQL server. Does anyone know how to approach this problem? I tried npm MySQL module but it seems the connection doesn't work as it is client side. Is there any other way of doing it? I need an idea to get me started.

问候

推荐答案

您需要一台服务器来处理来自的请求您的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.

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

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