Mysql – How to thesql database connection with react js

mysqlnode.jsreactjs

I'm beginner for React JS. Therefore, I want to learning how can used together React JS, Node JS and MySQL. So, Please give me some advises and example. I try do solve this problem. please help me guys.

Best Solution

You can't add back-end activity using ReactJs.

In Nodejs is possible.

You can connect MySql using sequelize ORM in nodejs.

Sequelize ORM

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, SQLite and Microsoft SQL Server. It has many solid features for transaction, relations, read replication and more.

Try this:

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

Setting up Sequelize MySQL connection

./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;

Create Sequelize model

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

Route

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

Controller

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