首页 > 解决方案 > 如何使用 React js 连接 mysql 数据库

问题描述

我是 React JS 的初学者。因此,我想学习如何将 React JS、Node JS 和 MySQL 一起使用。所以,请给我一些建议和例子。我试着解决这个问题。请帮帮我。

标签: mysqlnode.jsreactjs

解决方案


您不能使用 ReactJs 添加后端活动。

在 Nodejs 中是可能的。

您可以在 nodejs 中MySql使用连接。sequelize ORM

续集 ORM

Sequelize 是一个基于 Promise 的 Node.js ORM,用于 Postgres、MySQL、SQLite 和 Microsoft SQL Server。它具有许多可靠的事务、关系、读取复制等特性。

试试这个:

>npm install --save sequelize
>npm install --save mysql2

设置 Sequelize MySQL 连接

./app/config/env.js

const env = {
  database: 'testdb',
  username: 'root',
  password: '12345',
  host: 'localhost',
  dialect: 'mysql',
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
};
 
module.exports = env;

./app/config/db.config.js

const env = require('./env.js');
 
const Sequelize = require('sequelize');
const sequelize = new Sequelize(env.database, env.username, env.password, {
  host: env.host,
  dialect: env.dialect,
  operatorsAliases: false,
 
  pool: {
    max: env.max,
    min: env.pool.min,
    acquire: env.pool.acquire,
    idle: env.pool.idle
  }
});
 
const db = {};
 
db.Sequelize = Sequelize;
db.sequelize = sequelize;
 
//Models/tables
db.customers = require('../model/customer.model.js')(sequelize, Sequelize);
 
 
module.exports = db;

创建 Sequelize 模型

module.exports = (sequelize, Sequelize) => {
  const Customer = sequelize.define('customer', {
    firstname: {
    type: Sequelize.STRING
    },
    lastname: {
    type: Sequelize.STRING
    },
    age: {
      type: Sequelize.INTEGER
    }
  });
  
  return Customer;
}

路线

./app/controller/customer.route.js

module.exports = function(app) {
 
    const customers = require('../controller/customer.controller.js');
 
    // Create a new Customer
    app.post('/api/customers', customers.create);
 
    // Retrieve all Customer
    app.get('/api/customers', customers.findAll);
 
    // Retrieve a single Customer by Id
    app.get('/api/customers/:customerId', customers.findById);
 
    // Update a Customer with Id
    app.put('/api/customers/:customerId', customers.update);
 
    // Delete a Customer with Id
    app.delete('/api/customers/:customerId', customers.delete);
}

控制器

const db = require('../config/db.config.js');
const Customer = db.customers;
 
// Post a Customer
exports.create = (req, res) => {  
  // Save to MySQL database
  Customer.create({  
    firstname: req.body.firstname,
    lastname: req.body.lastname,
    age: req.body.age
  }).then(customer => {    
    // Send created customer to client
    res.send(customer);
  });
};
 
// FETCH all Customers
exports.findAll = (req, res) => {
  Customer.findAll().then(customers => {
    // Send all customers to Client
    res.send(customers);
  });
};
 
// Find a Customer by Id
exports.findById = (req, res) => {  
  Customer.findById(req.params.customerId).then(customer => {
    res.send(customer);
  })
};
 
// Update a Customer
exports.update = (req, res) => {
  const id = req.params.customerId;
  Customer.update( { firstname: req.body.firstname, lastname: req.body.lastname, age: req.body.age }, 
           { where: {id: req.params.customerId} }
           ).then(() => {
           res.status(200).send("updated successfully a customer with id = " + id);
           });
};
 
// Delete a Customer by Id
exports.delete = (req, res) => {
  const id = req.params.customerId;
  Customer.destroy({
    where: { id: id }
  }).then(() => {
    res.status(200).send('deleted successfully a customer with id = ' + id);
  });
};

服务器.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json())
 
const db = require('./app/config/db.config.js');
  
// force: true will drop the table if it already exists
db.sequelize.sync({force: true}).then(() => {
  console.log('Drop and Resync with { force: true }');
});
 
require('./app/route/customer.route.js')(app);
 
// Create a Server
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port)
})

推荐阅读