如何将MySQL数据库连接到ReactJS应用程序? [英] How to connect MySQL database to ReactJS app?

查看:1113
本文介绍了如何将MySQL数据库连接到ReactJS应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用create-react-app构建了一个Todo应用程序.我正在使用的商店基于本地存储(对象窗口的JS属性).现在,我创建了一个MySQL数据库,并希望连接到该数据库,因此状态将显示数据库中的值,并将通过操作进行更新.

I have build a Todo App with create-react-app. The store I'm using is based on Local Storage(JS attribute of object window). Now I created a MySQL databases and want to connect to that database, so the state will show the values from database, and will be updated through actions.

我尝试使用db.js通过节点"控制台连接到db并输出值.可以.

I've tried to connect to db and output values through 'node' console using db.js. It works.

const mysql = require('mysql');

const con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "root",
  database: 'root'
});

con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM tasks", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

是否可以使用此脚本将应用程序的状态连接到数据库?

Is it possible to connect the state of app to database using this script?

推荐答案

您不能直接连接它们.

在网络浏览器中运行的JavaScript不能说MySQL协议(也不能建立使用JS编写实现所需的 raw 网络连接).

JavaScript running in a web browser cannot speak the MySQL protocol (nor can it make raw network connections that would be needed to write an implementation in JS).

相反,创建一个Web服务(使用您选择的编程语言,它可以是在Node.js上运行的JavaScript(例如,您已经拥有的代码+ Express.js +一些胶水),然后使用Ajax与之通信.

Instead, create a web service (in the programming language of your choice, which could be JavaScript running on Node.js (e.g. the code you have already + Express.js + some glue) and use Ajax to communicate with it.

这篇关于如何将MySQL数据库连接到ReactJS应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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