Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

javascript - How to connect MySQL database to ReactJS app?

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The general solution for a question like this is the following framework:

  • Back-end (Node.js, Express, Database connection including authorization)
  • Front-end (React(, Redux to manage state))

If you then launch the React app, it should populate its state based on data retrieved from the database, which is a process to which you can add authorization (make retrievable data depend on the role/status of the user).

In the back-end you can define functions that take in a certain subset of parameters, which performs database actions, to which you can add business rules for your application. The React app then just sends HTTP requests to the Express server, which handles everything that needs verification and authorization before even touching the data.

If you search the internet for any configuration of a fullstack architecture using React and MySQL, you'll find similar results to what I mentioned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...