如何使用React JS进行MySQL数据库连接

时间:2019-03-28 09:15:27

标签: mysql node.js reactjs

我是React JS的初学者。因此,我想学习如何将React JS,Node JS和MySQL一起使用。因此,请给我一些建议和示例。我尽力解决这个问题。请帮助我。

2 个答案:

答案 0 :(得分:2)

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

在Node.js中是可能的。

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

  

序列化ORM

     

Sequelize是用于Postgres,MySQL,SQLite和Microsoft SQL Server的基于承诺的Node.js ORM。它具有用于事务,关系,读取复制等的许多可靠功能。

尝试一下:

>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);
  });
};

Server.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)
})

答案 1 :(得分:0)

app.js的后端文件夹中,就像您创建的后端中的server.js一样,添加以下代码:

const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user:'root',
password:'mysqljs123',//password of your mysql db
database:'react-sql-db'
});