如何将 MySQL 连接到 ReactJS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44898051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 22:22:29  来源:igfitidea点击:

How to connect MySQL to ReactJS

mysqlnode.jsdatabasereactjsdatabase-connection

提问by arslan

How can I connect MySQL to ReactJS? Are there any examples or tutorials which explain this that I can follow?

如何将 MySQL 连接到 ReactJS?是否有任何示例或教程可以解释这一点,我可以遵循?

I wrote the following code, but get errors:

我写了以下代码,但得到错误:

var React = require('react');
var ReactDOM = require('react-dom');

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

var fs = require('fs');

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : ' ',
    database : 'node'
});

connection.connect();

app.post('/users', function(req, res) {

    var user = req.body;

    var query = connection.query('INSERT INTO signup SET ?', user,  function(err, result) {

    });
    res.end('Success');
});

What is wrong with this code?

这段代码有什么问题?

回答by Farid Nouri Neshat

The error you mentioned in the comments, it's because you are trying to require fsmodule, however in doesn't exist in the front-end with webpack by default. Of course you could provide a polyfillbut that's not what's being asked here.

您在评论中提到的错误,是因为您正在尝试 requirefs模块,但是默认情况下,在 webpack 的前端中不存在。当然,您可以提供一个 polyfill,但这不是这里要问的。

So let's take a step back. How can one connect to MySQL?

所以让我们退后一步。如何连接到MySQL?

The usual method to connect to MySQL is making a TCP connection, well normally MySQL driver does this for you so you don't need to know exactly how, but this means you can't really connect from Javascript on browser.

连接到 MySQL 的常用方法是建立 TCP 连接,通常 MySQL 驱动程序会为您执行此操作,因此您无需确切知道如何进行,但这意味着您无法真正从浏览器上的 Javascript 进行连接

However you can do this in the backend/server-side with node.js or any other server-side language. The way normally this is done is that, the backend exposes an HTTP(s) API that can be accessed by the front-end. This could be a REST API, GraphQL, or even something as complex as SOAP(which I don't suggest) and through this API, the database is exposed. This is a common design in the usual web applications and tiered architectures.

但是,您可以使用 node.js 或任何其他服务器端语言在后端/服务器端执行此操作。通常这样做的方式是,后端公开一个可由前端访问的 HTTP(s) API。这可能是一个 REST API、GraphQL,甚至是像SOAP一样复杂的东西(我不建议这样做),通过这个 API,数据库是公开的。这是通常的 Web 应用程序和分层架构中的常见设计。

Meanwhile, you can with Mysql Labs HTTP plugin, you can expose your database to the browser without writing any API of your own, but of course if you go that path, you gotta know what your doing and have top security standards.

同时,您可以使用Mysql Labs HTTP 插件,您可以将您的数据库暴露给浏览器,而无需编写您自己的任何 API,但是当然,如​​果您走这条路,您必须知道自己在做什么并拥有最高的安全标准。