How to mysql database connection with react js [duplicate] - mysql

This question already has answers here:
How to connect MySQL database to ReactJS app?
(2 answers)
MySQL with Node.js
(9 answers)
Closed 3 years ago.
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.

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

In app.js at the backend folder that is like server.js in the backend that you made add these code :
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user:'root',
password:'mysqljs123',//password of your mysql db
database:'react-sql-db'
});

Related

Add Data in Mongodb and Mysql in single button click

In this application i am adding data in mongodb which is working fine but at same time i need to implement Mysql. So when i register a user it should get save in Mongodb and in Mysql. My Code for Mysql Data Connection is sucessfull but data pushing is not happening(Mysql). Can anyone help me out yr. Thank you very much.
const {Sequelize} =require('sequelize');
const mysql= require('mysql');
var path1 = require('path');
var root_path = path1.dirname(require.main.filename);
var models = require(root_path+'/models');
router.post("/users", function(req, res) {
console.log("First In");
var user_id=req.query.user_id
var flag;
var userData = [];
var body_data =req.body.data;
//Mysql Start
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'tcexam'
});
con.connect((err) => {
if(err){
console.log('Error connecting to Db',err);
return;
}
console.log('Connection established');
});
models.userMysl.find({
email: body_data.email.toLowerCase()
})
console.log("Email---------->>>",email);
.then(function(country){
models.userMysl.create({
name: body_data.user_firstName,
lastname : body_data.user_lastname,
mother_name : body_data.motherName,
surname : body_data.Surname,
email: body_data.userEmail.toLowerCase(),
username:body_data.user_name,
password:body_data.user_password,
}).then(function(user) {
if(error){
console.log("Error",error);
}else {
res.send({
status: 200,
data:userData
});
}
});
});
});
//Mysql End
userModel.find({
"role": req.query.user_type
}).then(function(users) {
users.forEach(user => {
if(user.doc_id==''){
var user = {
id: user._id,
name: user.fullName,
status: user.status,
role: user.role,
email:user.email,
lastLoginDate: user.lastLoginDate,
lastLoginTime: user.lastLoginTime,
flag:'0'
}
userData.push(user);
}
else{
var usr = {
id: user._id,
name: user.fullName,
picture: `${filelink}/api/usersData/download?document_id=${user.doc_id}`,
status: user.status,
role: user.role,
email:user.email,
lastLoginDate: user.lastLoginDate,
lastLoginTime: user.lastLoginTime,
flag:'1'
}
userData.push(usr);
}
})
res.send({
status: 200,
data: userData
})
})
"use strict";
module.exports = function(sequelize, DataTypes) {
var userMysql = sequelize.define("tce_users", {
user_name: DataTypes.STRING(100),
user_password: DataTypes.STRING,
surname: DataTypes.STRING(100),
user_email: DataTypes.STRING(100),
user_firstName:DataTypes.STRING(100),
user_lastname:DataTypes.STRING(100),
user_birthdate:DataTypes.String(17),
user_birthplace:Datatypes.STRING(100),
user_regnumber:DataTypes.STRING(100),
user_ssn:DataTypes.STRING(100),
user_level:DataType.STRING(100),
user_verifycode:Datatypes.STRING(100)
});
return userMysql;
};
Since, Node JS is single threaded, after insertion into mysql line of code executes before establishment of connection with mysql db. Somehow connecting with mysql require time therefore next block code executes before connection happen.
Firstly, you need to change approach where you need to connect mysql,
Connection string probably should not be in the post api itself,
it's needs to be connect when application starts using some config utility.
Either you can choose promise to resolve the execution of insertion into
mysql or can use async await approach to insert the data after mysql
connection established.

Table '[database-name].sessions' doesn't exist - using express-session

Here is some sample code that outlines my issue. I'm trying to get express-session / connect-session-sequelize to work for a website with login functionalities.
However, when I try to call my POST request, I get the following error:
I can only assume it's trying to store session data onto my database, but cannot find a table. I can bypass this by going in and creating the table manually with all the columns it wants, but I'm wondering if there's an issue in my code preventing the package from working properly (or if this is how it's supposed to work.)
require('dotenv').config({ path: './config/.env' })
const express = require('express')
const session = require('express-session')
const mysql = require('mysql2')
const Sequelize = require('sequelize')
const path = require('path')
const SequelizeStore = require('connect-session-sequelize')(session.Store)
const app = express()
const PORT = 9999
app.use(express.json())
app.use(express.static(path.join(__dirname, 'public')))
// Allowing connection to database in Workbench
const db = new Sequelize('somedatabase', 'root', process.env.PASSWORD, {
host: 'localhost',
dialect: 'mysql'
})
db.authenticate()
.then(() => {
console.log('Connected...')
}).catch(error => {
console.log('Failed to connect...', error)
})
// Setting up session
app.use(session({
secret: 'shhh',
store: new SequelizeStore({
db: db
}),
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 1000000
}
}))
// Sample model
const User = db.define('user', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
username: Sequelize.STRING,
password: Sequelize.STRING
})
// Sample request
app.post('/api/create', async (req, res) => {
const newUser = {
username: john,
password: verysecurepassword
}
await User.create(newUser)
})
app.listen(PORT, () => {
console.log(`Listening on localhost:${PORT}...`)
})
In this code, you are using several packages: express-session, which manages the session itself but delegates how the session is saved to connect-session-sequelize.
So the problem is that connect-session-sequelize is trying to save session data in the database, but it cannot because there is no table for sessions.
As written in the documentation of this package (https://www.npmjs.com/package/connect-session-sequelize):
If you want SequelizeStore to create/sync the database table for you, you can call sync() against an instance of SequelizeStore along with options if needed.
So try creating the store, attaching it to the session manager, and then
initializing it (I did not test this code):
// Setting up session
var myStore = new SequelizeStore({
db: db
});
app.use(
session({
secret: "shhh",
store: myStore,
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 1000000
}
})
);
myStore.sync();

TypeError: require(...) is not a function while Using sequalize with node js

I am beginner in web dev and trying to create a Full stack project using Mysql Express React Node js.
Facing this TypeError issue while using Sequalize with node js.
I'm new to this and I can't understand the problem. Can someone please explain it to me and help me find a solution?
(PS: If you guys need any other file let me know)
server js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
const db = require("./models");
db.sequelize.sync({ force: true }).then(() => {
console.log("Drop and re-sync db.");
});
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome." });
});
require("./src/routes/routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
index js
const dbConfig = require("../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.devices = require("./devices.js")(sequelize, Sequelize);
module.exports = db;
devices js
module.exports = (sequelize, Sequelize) => {
const Device = sequelize.define("devices", {
serialno: {
type: Sequelize.INTEGER
},
brand: {
type: Sequelize.STRING
},
modelname: {
type: Sequelize.STRING
}
});
return Device;
};
error
db.devices = require("./devices.js")(sequelize, Sequelize);
^
TypeError: require(...) is not a function
at Object.<anonymous> (C:\Users\theta\Documents\project\src\models\index.js:22:37)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (C:\Users\theta\Documents\project\src\server.js:19:12)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
Try to change this on index.js:
db.devices = require("./devices.js")(sequelize, Sequelize);
To this:
const path = require('path')
db.devices = require(path.join(__dirname, 'devices'))(sequelize, Sequelize);
Here's what works for me in TypeScript (using sequelize version 6.17.0):
config.ts
import { Sequelize } from 'sequelize'
const dbName = 'test-db'
const dbUser = 'test-user'
const dbPass = '123123'
const dbHost = 'some-host'
// new Sequelize(name, user, password, options)
export const sequelize = new Sequelize(dbName, dbUser, dbPass, {
host: dbHost,
dialect: 'postgres',
port: 3306,
dialectOptions: {
multipleStatements: true,
},
pool: {
max: 5,
min: 0,
idle: 10000,
},
logging: false,
})
Let's say we have a models/ folder with three files: User.ts, Member.ts and index.ts.
models/User.ts → we must use module.exports here
module.exports = (sequelize: any, DataTypes: any) => {
const User = sequelize.define(
'user',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true,
},
email: {
type: DataTypes.STRING(250),
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
allowNull: true,
defaultValue: null,
},
},
{
timestamps: true,
underscored: true,
tableName: 'user',
indexes: [{ unique: true, fields: ['email'] }],
}
)
User.associate = (models: any) => {
User.hasOne(models.Member, { as: 'Member', foreignKey: 'id' })
}
return User
}
models/index.ts
import fs from 'fs'
import path from 'path'
import Sequelize from 'sequelize'
import { sequelize } from './config.js'
// current file basename
const basename = path.basename(__filename)
// our db object
const db: any = {}
// so we don't reload unecessarily
let loaded = false
const createModels = () => {
// if already loaded, return cached object
if (loaded) return db
// create an array of model files' basenames
const filenames = fs.readdirSync(__dirname).filter((file: string) => {
return (
// filter out the current `index.ts` file
file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.ts'
)
})
filenames.map((file: any) => {
// use `require` to load our models
const model = require(path.join(__dirname, file))(
sequelize,
Sequelize.DataTypes
)
db[model.name] = model
})
// run `.associate` if applicable
Object.keys(db).map((model) => {
if (db[model].associate) {
db[model].associate(db)
}
})
// attach both our instance and Sequelize to our db object
db.sequelize = sequelize
db.Sequelize = Sequelize
loaded = true
return db
}
export default createModels()
export { createModels }
Let me know how it goes.
If you are tying to import any file for example a font file, then create a mockFile that just have
// mockFile.ts or mockFile.js
export default {};
and then in jest.config.js
moduleNameMapper: {
'^.+\\.(woff2)$': '<rootDir>/<path to file>/mockFile.ts',
},
This will resolve to the mockFil when it will try to import a font file. You can also add other file extentions like '^.+\\.(jpg|png|woff2)$: '<rootDir>/<path to file>/mockFile.ts'.

Node.js MySQL model designing

I'm developing a node.js application using MySQL database but I'm stuck with making models on the node.js side of my application. I've used Mongoose before to produce schemas and use models to do database functions but i couldn't find such support for MySQL. Can anyone suggest a proper way to isolate my database functions in node.js like I could do with Mongoose. here's my app.js and users model i'm using right now.
app.js
var express= require("express");
var bodyParser = require("body-parser");
var mysql = require("mysql");
var UserModel= require("./models/User.js")
var app=express();
var sql = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "dricm"
});
sql.connect(function (err) {
if(err){
console.log("error");
}else{
console.log("connected");
}
});
app.set("views", "./views");
app.use(express.static("node_modules/bootstrap/dist"));
app.use(express.static("public"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.get('/', function (req, res) {
res.render("signup.jade");
});
app.post('/signup', function (req, res) {
var obj= {
username: req.body.username,
password: req.body.password
};
UserModel.createUser(obj);
res.redirect("/");
});
app.listen(3000, function () {
console.log("server running at 3000");
});
User.js (probable model)
var mysql= require("mysql");
var bcrypt = require("bcryptjs");
var sql = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "dricm"
});
sql.connect(function (err) {
if(err){
console.log("error");
}else{
console.log("connected");
}
});
var User= {
}
User.createUser = function createUser(newUser) {
bcrypt.genSalt(10, function(err, salt){
bcrypt.hash(newUser.password,salt, function (err, hash) {
newUser.password = hash;
var query = sql.query("INSERT INTO USERS set ?", newUser, function (err, res) {
console.log(query);
if(err) {
console.log("error");
}
else{
console.log(res.insertId);
}
});
});
});
}
module.exports= User;
What you are looking for is called an ORM (Object-relational mapping) Mongoose is one for MongoDB (Which is a NOSQL document oriented database)
There are other ORMs for relational databases that work with Node.js, The most popular right now is Sequelize which I have personally used and recommend.
With Sequelize you can put your models in different files just like Mongoose however in order to load them on, you need to add them with a simple script inside your index.js
Imagine the following Workspace:
--models/
----User.js
----Permissions.js
--index.js
And your model definitions should be something like this:
User.js
const UserModel = (sequelize, Sequelize) => {
const {INTEGER, STRING, FLOAT, BOOLEAN, DATE} = Sequelize
const User = sequelize.define('User', {
UserId: {type: INTEGER, primaryKey: true, autoIncrement: true},
Username: {type: STRING, primaryKey: true, allowNull: false},
Password: STRING
})
return User
}
module.exports = UserModel
Permissions.js
const PermissionsModel = (sequelize, Sequelize) => {
const {INTEGER, STRING, FLOAT, BOOLEAN, DATE} = Sequelize
const Permissions = sequelize.define('Permissions', {
Role: {type: STRING, allowNull: false},
ControllerAddress: {type: STRING, allowNull: false}
})
return Permissions
}
module.exports = PermissionsModel
Now you need to use the following script to use them inside your index.js
let normalizedPath = require('path').join(__dirname, "models")
require('fs').readdirSync(normalizedPath).forEach((file) => {
sequelize.import('./models/' + file)
})
let {User, Permissions} = sequelize.models
Now you can use the User and Permissions instances to control them and call functions like:
User.create({Username, Password})

Persistent Session in Nodejs using MySql

new to nodejs. this might be a silly/easy question
I have an Express App and i am using mysql for persistent sessions. (using express-mysql-session to do that).
Here's code snippet from app.js:
var express = require('express');
var session = require('express-session');
var SessionStore = require('express-mysql-session');
var app = express();
app.use(session({
store: new SessionStore({
host: 'localhost',
user: 'test',
password: 'test',
database: 'test'
}),
secret: 'secret_key',
resave: false,
saveUninitialized: false
}));
routes.js
module.exports = function(app) {
app.post('/login', wrap(function* (req, res) {
var email = req.body.email;
var password = req.body.password;
var response = yield new AccountController().login(email, password);
if (response.status === 'success') {
req.session.account = {
accountId: response.accountId,
accountStatus: response.accountStatus
};
req.session.save(function(err) {
if (err) console.log('error in saving session: ' + err);
});
}
}
}));
The get and set method of express-mysql-session are called everytime a request is sent.
I wanted to know how can i set my custom data into the persistent session store without using any other library like passport.
and also how to read the store too.