MY SQL Sequelize Unique Value not working as intended - mysql

I am trying to code a website to work with ReactJS, NodeJs and MySQL.
I have been using Sequelize and it works but i realised that it allows all usernames even those that are used.
i set the value to be Unique in the JS file.
I have followed this website (https://sequelize.org/docs/v6/core-concepts/validations-and-constraints/) but to no success.
module.exports = (sequelize,DataTypes) =>{
const Users = sequelize.define("Users", {
username:{
type: DataTypes.TEXT,
allownull: false,
unique: true
},
userpass:{
type: DataTypes.STRING,
allownull: false,
},
usergroup:{
type: DataTypes.STRING,
allownull: false,
},
});
return Users;
}
The code i am running
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const mysql = require('mysql2');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "testschema"
})
const db = require('./models');
// Routers
const userRouter = require('./routes/user-routes');
app.use("/users", userRouter);
app.post('/testing', (req, res) => {
console.log("testing route");
console.log(req.body);
res.send("Testing Route");
})
app.post('/login', async (req, res) => {
const username = req.body.username
const userpass = req.body.userpass
console.log("Line 9", req.body)
console.log("backend triggered");
const loginInfo = await new Promise((resolve, reject) => {
connection.query("SELECT * FROM users WHERE username = ? AND userpass = ?", [username, userpass], (err, result) => {
if (err) {
console.log(err)
}
else {
if (result.length > 0) {
console.log("Success" + result);
resolve(result)
}
else {
console.log("Wrong username/password")
}
}
})
});
console.log(loginInfo)
})
;
app.post('/register', async (req, res) => {
const username = req.body.username
const userpass = req.body.userpass
console.log("Line 83", req.body)
console.log("backend triggered");
const registerInfo = await new Promise((resolve, reject) => {
connection.query("INSERT INTO users (username, userpass,createdAt,updatedAt) VALUES (?,?,0,0)", [username, userpass], (err, result) => {
if (err) {
console.log(err)
}
})
});
console.log(registerInfo)
})
connection.connect((err) => {
if (err) {
console.log("Error occurred", err);
} else {
console.log("Connected to MySQL Server");
}
});
db.sequelize.sync().then(() => {
app.listen(8000, () => {
console.log("Server is up on port 8000");
});
});
This is what i get in the backend
Connected to MySQL Server
Executing (default): CREATE TABLE IF NOT EXISTS `Users` (`id` INTEGER NOT NULL auto_increment , `username` TEXT UNIQUE, `userpass` VARCHAR(255), `usergroup` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `Users` FROM `testschema`
Server is up on port 8000
Line 83 { username: 'blueflag', userpass: 'blueflag' }
backend triggered

Related

when entering a new row in child table, how do i populate the foreign key ticketId using sequelize nodejs?

I am trying to figure out how I can populate the foreign key in my child table(subTaskTickets) from the parent table (Tickets).
When i create a Ticket, then I create a subTaskTicket, the ticketID and ETR_ID remain null and dont populate with the id from Ticket table.
Not sure how I can do this as i am new with sequelize, nodejs and mysql.
Here are my 2 modals:
SubTaskTicket model (child)
const Sequelize = require("sequelize-v5");
const sequelize = require("../connection");
//create a new Date object with the current date and time
const date = new Date();
//extract the year and month from the date
const year = date.getFullYear();
const month = date.getMonth() + 1;
//combine the year and month into a single string to be concat with id to form ETR_ID
const yearMonth = year.toString().concat("-", month.toString(), "-ST");
const SubTaskTicket = sequelize.define("subTaskTicket", {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
ETR_ID: {
type: Sequelize.STRING,
// primaryKey: true,
// defaultValue: ""
allowNull: true,
references: {
model: 'tickets',
key: 'ETR_ID'
}
},
subTaskId: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
defaultValue: "",
primaryKey: true
},
Title: {
type: Sequelize.STRING,
allowNull: false
},
Description: {
type: Sequelize.STRING,
allowNull: false
},
Status: {
type: Sequelize.CHAR,
allowNull: false
},
ETR: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: yearMonth
},
});
module.exports = SubTaskTicket;
Ticket model (Parent)
const Sequelize = require('sequelize-v5');
const sequelize = require('../connection');
//create a new Date object with the current date and time
const date = new Date();
//extract the year and month from the date
const year = date.getFullYear();
const month = date.getMonth()+1;
//combine the year and month into a single string to be concat with id to form ETR_ID
const yearMonth = year.toString().concat('-', month.toString(),'-');
const Tickets = sequelize.define('tickets', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
ETR_CAT:{
type: Sequelize.STRING,
allowNull: false
},
ETR_ID: {
type: Sequelize.STRING,
primaryKey: true,
unique: true,
defaultValue: ""
},
Title: {
type: Sequelize.STRING,
allowNull: false
},
Description:{
type: Sequelize.STRING,
allowNull: false
},
ETR: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: yearMonth
}
});
module.exports = Tickets;
Here is my app.js file containing express etc:
const express = require("express");
const cors = require("cors");
const app = express();
const sequelize = require("./connection");
const Tickets = require("./models/ticket.model");
const SubTaskTicket = require('./models/subTaskTicket.model');
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to Tylers application." });
});
require("./routes/ticket.routes")(app);
Tickets.hasMany(SubTaskTicket, {
as: 'subtaskticket'
});
SubTaskTicket.belongsTo(Tickets);
Tickets.hasMany(SubTaskTicket);
//will create tables from our modals, but also define relations in our DB
// sync() command for dev, add { force: true } so i can remake tables from scratch right away
sequelize.sync().then(result => {
console.log(result);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
})
.catch(err => {
console.log(err);
});
Next are my 2 controllers for each model:
subTaskTicket controller
const Sequelize = require("sequelize-v5");
const sequelize = require("../connection");
const subTaskTicket = require("../models/subTaskTicket.model");
//Sequelized create format
exports.createTicket = (req, res, next) => {
const Title = req.body.Title;
const Description = req.body.Description;
const Status = req.body.Status;
// const ETR = req.body.ETR;
subTaskTicket.create({
Title: Title,
Status: Status,
Description: Description,
//ETR: ETR
})
.then(result => {
//console.log(result);
console.log("Created Ticket");
sequelize.query('update subtasktickets set subTaskId = concat(ETR,id)');
})
.catch(err => {
console.log(err);
})
}
//Sequelized findAll
exports.findAllTickets = (req, res, next) => {
subTaskTicket.findAll({include: ["subtaskticket"]})
.then(data => {
res.send(data);
}).catch(err => {
console.log(err);
});
}
// Sequelized Find a single Tutorial with a id
exports.findOneTicket = (req, res) => {
const id = req.params.id;
subTaskTicket.findByPk(id)
.then(data => {
if (data) {
res.send(data);
} else {
res.status(404).send({
message: 'Cannot find Child Ticket with id = ' + id
});
}
})
.catch(err => {
res.status(500).send({
message: 'Error retrieving child Ticket with id= ' + id
});
});
};
//Sequilized Update Ticket identified by the id in the req
exports.updateTicket = (req, res) => {
const id = req.params.id;
subTaskTicket.update(req.body, {
where: { id: id }
})
.then(num => {
if (num == 1) {
res.send({
message: "Child Ticket was updated successfully."
});
} else {
res.send({
message: `Cannot update Child Ticket with id=${id}. Maybe Child Ticket was not found or req.body is empty!`
});
}
})
.catch(err => {
res.status(500).send({
message: "Error updating Ticket with id=" + id
});
});
};
// Sequilized Delete a Ticket with the specified id in the request
exports.deleteTicket = (req, res) => {
const id = req.params.id;
subTaskTicket.destroy({
where: { id: id }
})
.then(num => {
if (num == 1) {
res.send({
message: "Child Ticket was deleted successfully!"
});
} else {
res.send({
message: `Cannot delete Child Ticket with id= ${id}. Maybe Child Ticket was not found!`
});
}
})
.catch(err => {
res.status(500).send({
message: "Could not delete Ticket with id=" + id
});
});
};
ticket.controller
const Sequelize = require("sequelize-v5");
const sequelize = require("../connection");
const Tickets = require("../models/ticket.model");
const { Op } = require("sequelize-v5");
//Sequelized create format
exports.createTicket = (req, res, next) => {
const ETR_CAT = req.body.ETR_CAT;
const Title = req.body.Title;
const Description = req.body.Description;
const ticketId = req.body.ticketId
Tickets.create({
ETR_CAT: ETR_CAT,
Title: Title,
Description: Description,
})
.then(result => {
//console.log(result);
console.log("Created Ticket");
sequelize.query('update tickets set ETR_ID = concat(ETR,id)');
})
.catch(err => {
console.log(err);
})
}
//Sequelized findAll
exports.findAllTickets = (req, res, next) => {
Tickets.findAll({include: ["subtaskticket"]})
.then(data => {
res.send(data);
}).catch(err => {
console.log(err);
});
}
// Sequelized Find a single Tutorial with a id
exports.findOneTicket = (req, res) => {
const id = req.params.id;
Tickets.findByPk(id, {include: ["subtaskticket"]})
.then(data => {
if (data) {
res.send(data);
} else {
res.status(404).send({
message: 'Cannot find Ticket with id = ' + id
});
}
})
.catch(err => {
res.status(500).send({
message: 'Error retrieving Ticket with id= ' + id
});
});
};
//Sequilized Update Ticket identified by the id in the req
exports.updateTicket = (req, res) => {
const id = req.params.id;
Tickets.update(req.body, {
where: { id: id }
})
.then(num => {
if (num == 1) {
res.send({
message: "Ticket was updated successfully."
});
} else {
res.send({
message: `Cannot update Ticket with id=${id}. Maybe Ticket was not found or req.body is empty!`
});
}
})
.catch(err => {
res.status(500).send({
message: "Error updating Ticket with id=" + id
});
});
};
// Sequilized Delete a Ticket with the specified id in the request
exports.deleteTicket = (req, res) => {
const id = req.params.id;
Tickets.destroy({
where: { id: id }
})
.then(num => {
if (num == 1) {
res.send({
message: "Ticket was deleted successfully!"
});
} else {
res.send({
message: `Cannot delete Ticket with id= ${id}. Maybe Ticket was not found!`
});
}
})
.catch(err => {
res.status(500).send({
message: "Could not delete Ticket with id=" + id
});
});
};
and this is my routes:
module.exports = app => {
const tickets = require("../controllers/ticket.controller");
const subTaskTicket = require("../controllers/subTaskTicket.controller")
var router = require("express").Router();
// Create a new Tutorial
router.post("/addTicket", tickets.createTicket);
router.post("/addSubTicket", subTaskTicket.createTicket);
// Retrieve all Tickets
router.get("/allTickets", tickets.findAllTickets);
// Retrieve a single Ticket with id
router.get("/ticket/:id", tickets.findOneTicket);
// Update a Ticket with id
router.put("/updateTicket/:id", tickets.updateTicket);
// Delete a Ticket with id
router.delete("/deleteTicket/:id", tickets.deleteTicket);
// // Delete all Tickets
// router.delete("/", tickets.deleteAll);
app.use("/api/tickets", router);
};
Any ideas on what i am missing or how I can create a row in the subTaskTicket table that would populate the foreign keys with the proper id?
when i integrate this with a frontend (angular) I want Ticket to be the main ticket (ex has id =1) and then i can create "sub tickets" that would be tasks under that main ticket. So they would populate the subtaskticket table and be tied into that parent Ticket with the id = 1.
Any help would be appreciated! as i am stuck and trying to figure this out while using sequelize
Below is the query that is generated when i run my nodemon command. This is using sequelize.sync() in app.js to make the tables when i first create it.
Executing (default): CREATE TABLE IF NOT EXISTS `tickets` (`id` INTEGER NOT NULL auto_increment , `ETR_CAT` VARCHAR(255) NOT NULL, `ETR_ID` VARCHAR(255) DEFAULT '' UNIQUE , `Title` VARCHAR(255) NOT NULL, `Description` VARCHAR(255) NOT NULL, `ETR` VARCHAR(255) NOT NULL DEFAULT '2022-12-', `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`, `ETR_ID`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `tickets`
Executing (default): CREATE TABLE IF NOT EXISTS `subTaskTickets` (`id` INTEGER NOT NULL auto_increment , `ETR_ID` VARCHAR(255), `subTaskId` VARCHAR(255) NOT NULL DEFAULT '' UNIQUE , `Title` VARCHAR(255) NOT NULL, `Description` VARCHAR(255) NOT NULL, `Status` CHAR(255) NOT NULL, `ETR` VARCHAR(255) NOT NULL DEFAULT '2022-12-ST', `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `ticketId` INTEGER, PRIMARY KEY (`id`, `subTaskId`), FOREIGN KEY (`ETR_ID`) REFERENCES `tickets` (`ETR_ID`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `subTaskTickets`
You need to choose only one auto-generated column as a primary key in both models
You need to indicate a foreign key column in associations explicitly (and the same for both paired associations) since you use the non-default name for it:
Tickets.hasMany(SubTaskTicket, {
foreignKey: 'ETR_ID'
});
SubTaskTicket.belongsTo(Tickets, {
foreignKey: 'ETR_ID'
});

web browser crashes when using mysql prepared query with nodejs

I want to return the result of query to DB, which I think would be a promise and then consume that promise in another file.Here is my model code (User.js) :
User.prototype.login = function () {
return new Promise((resolve, reject) => {
pool.execute('SELECT * FROM `users` WHERE `username` = ? AND `password` = ?', [this.data.username, this.data.password], (err, attemptedUser) => {
if (err) {
pool.release();
return reject(err);
} else {
pool.release();
return resolve(attemptedUser);
}
});
});
}
and the code in my controller file (userController.js):
const User = require('../models/User');
exports.login = (req, res) => {
let user = new User(req.body);
user.login()
.then((result) => {
res.send(result);
})
.catch((err) => {
res.send(err);
});
};
But when I click on the login button the page doesn't go to the specified URL and keeps working until crash.
Where is the problem?
UPDATE-1
This is my db.js :
const mysql = require('mysql2/promise');
const dotenv = require('dotenv');
dotenv.config();
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: 100
});
module.exports = pool;

Error creating user manually in Node.js using Mysql Database "TypeError: User.findById is not a function

I need help on this error "TypeError: User.findById is not a function" when I create user manually and try to find the user by Id.
The portion of code with the error
sequelize
.sync()
.then(result => {
return User.findById(1);
})
.then(user => {
if (!user) {
return User.create({ name: 'john', email: 'john#test.com' });
}
return user;
})
.then(user => {
// console.log(user);
app.listen(3000);
})
.catch(err => {
console.log(err);
});
See my code below
user model
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
name: Sequelize.STRING,
email: Sequelize.STRING
});
module.exports = User;
App.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const errorController = require('./controllers/error');
const sequelize = require('./util/database');
const Product = require('./models/product');
const User = require('./models/user');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
User.findById(1)
.then(user => {
req.user = user;
next();
})
.catch(err => console.log(err));
});
app.use('/admin', adminRoutes);
app.use(shopRoutes);
app.use(errorController.get404);
Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);
sequelize
.sync()
.then(result => {
return User.findById(1);
})
.then(user => {
if (!user) {
return User.create({ name: 'john', email: 'john#test.com' });
}
return user;
})
.then(user => {
// console.log(user);
app.listen(3000);
})
.catch(err => {
console.log(err);
});
There is no method like Model.findById in sequelize v5. You can use Model. findByPk or Model.findOne like this:
Model.findOne({ where: { id: 1 } })

How can I make my Node.js MySQL connection as a promise work?

I have just started to work with node.js and my js knowledge is a bit rusty.
I started with callbacks and then I found out about promises. This syntax was more like my brain works, so I rewrote my code with promises.
But now my MySql connection does not work. It can't even get reached (I think...)
I have logged the word "test" in the file userDB, that worked. But then in the mySql file the console.log "test2" didn't work.
Thanks to you all!
Chris
Here is my server.js (the file that node starts):
/* REQUIRE */
const oAuth2Server = require('node-oauth2-server');
const express = require('express');
const bodyParser = require('body-parser');
const oAuthModel = require('./endpoints/auth/authModel');
const util = require('util');
const dbCon = require('./subsystem/mySql')
/* CONST */
const port = 3000;
const debug = true;
const app = express();
/* INIT */
app.oauth = oAuth2Server({
model: oAuthModel,
grants: ['password'],
debug: debug
})
/* ROUTER */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(app.oauth.errorHandler());
const authRoutes = require('./router/auth')(express.Router(), app, dbCon)
app.use('/auth', authRoutes);
app.all('*', (req, res) => {
res.status(404).send({message: "This service was not found"});
});
/* Start Server */
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
Here is my router file auth.js:
module.exports = (router, expressApp, dbCon) => {
const userDB = require('../endpoints/user/userDB')(dbCon)
const authMiddleware = require('../endpoints/auth/authMiddleware')
const userMiddleware = require('../endpoints/user/userMiddleware')(userDB)
router.post('/registerUser', userMiddleware.registerUser)
//router.post('/login', expressApp.oauth.grant(), authMiddleware.login)
router.post('/login', expressApp.oauth.grant())
return router
}
Here is my userDB file:
let mySqlConnection;
module.exports = injectedMySqlConnection => {
mySqlConnection = injectedMySqlConnection
return {
registerUserInDB: registerUserInDB,
getUserFromCrentials: getUserFromCrentials,
doesUserExist: doesUserExist,
getUserByUsername: getUserByUsername
}
}
const registerUserInDB = (username, password) => {
return new Promise((resolve,reject) => {
//execute the query to register the user
mySqlConnection.query(`INSERT INTO users (username, user_password) VALUES ('${username}', SHA('${password}'))`)
.then(data => {resolve(true)})
.catch(error => {reject(error)})
})
}
const getUserFromCrentials = (username, password) => {
return new Promise((resolve,reject) => {
//create query using the data in the req.body to register the user in the db
const getUserQuery = `SELECT * FROM users WHERE username = '${username}' AND user_password = SHA('${password}')`
console.log('getUserFromCrentials query is: ', getUserQuery);
//execute the query to get the user
mySqlConnection.query(getUserQuery)
.then(data => {resolve(data)})
.catch(error => {reject(error)})
})
}
const doesUserExist = username => {
return new Promise((resolve,reject) => {
console.log('test');
//execute the query to check if the user exists
mySqlConnection.query(`SELECT * FROM users WHERE username = '${username}'`)
.then(data => {resolve(data.results !== null ? data.results.length == 1 ? true : false : false)})
.catch(error => {reject(error)})
})
}
const getUserByUsername = username => {
return new Promise((resolve,reject) => {
//execute the query to check if the user exists
mySqlConnection.query(`SELECT id, username FROM users WHERE username = '${username}'`)
.then(data => {resolve(data)})
.catch(error => {reject(error)})
})
}
Here is my userMiddleware (is this middleware?):
let userDb;
module.exports = injectedUserDb => {
userDb = injectedUserDb
return {
registerUser: registerUser
}
}
function registerUser(req, res){
console.log(`authRoutesMethods: registerUser: req.body is:`, req.body);
//query db to see if the user exists already
userDb.doesUserExist(req.body.username)
.then(data => {
if(data)
{
sendResponse(res, "User already exists", 200)
return
}
else
{
//register the user in the db
userDb.registerUserInDB(req.body.username, req.body.password)
.then(data => {
userDb.getUserByUsername(req.body.username)
.then(data => {sendResponse(res, data.results, "")})
.catch(error => {sendResponse(res, "Failed to register user", error)})
})
.catch(error => {sendResponse(res, "Failed to register user", error)})
}
})
.catch(err => {
sendResponse(res, "User already exists", 200)
return
})
}
function sendResponse(res, message, error) {
res
.status(error !== null ? error !== null ? 400 : 200 : 400)
.json({
'message': message,
'error': error,
})
}
And last but not least my mySql.js file:
var mySql = require('mysql');
const query = sql => {
return new Promise( ( resolve, reject ) => {
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'oauth2test'
});
console.log('test2');
connection.query( sql, ( err, rows ) => {
if ( err )
{
connection.end();
reject( err );
}
else
{
connection.end();
resolve( rows );
}
});
});
}
module.exports.query = query;
You have a simple typo in your mySql.js file:
The line
var mySql = require('mysql');
should be replaced with
var mysql = require('mysql');
Other than that the query code works ok on my machine:
var mysql = require('mysql');
const query = sql => {
return new Promise( ( resolve, reject ) => {
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'oauth2test'
});
console.log('test2');
connection.query( sql, ( err, rows ) => {
if ( err )
{
connection.end();
reject( err );
}
else
{
connection.end();
resolve( rows );
}
});
});
}
module.exports.query = query;

how can i post data from reactjs form to mysql database

How can I send this data to database MySQL from a reactjs form? I'm a beginner in reactjs and I'm tired of trying.
In the back-end I use nodejs, express, and cors, so if u can tell me how because I have to finish this work.
The console returns GET Localhost 404 Not Found.
This is what I do but I don't know there is a better way to make it.
import React, { Component } from 'react'
import { Table,Button,
Modal,ModalHeader,
ModalBody,ModalFooter,
Label,Input,Form } from 'reactstrap';
export default class Db1 extends Component {
state = {
users: [],
newUserData: {
nom: '',
prenom: '',
adresse: '',
email: ''
},
newUserModal:false,
}
componentDidMount() {
this.getUsers();
}
getUsers = () => {
fetch('http://localhost:4000/users')
.then(response => response.json())
.then(response => this.setState({ users: response.data}))
.catch(err => console.error(err))
}
addUser = () => {
let { nom,prenom,adresse,email } = this.state.newUserData;
fetch(`http://localhost:4000/users/add?
nom=${nom}&prenom=${prenom}&adresse=${adresse}&email=${email}`,{
method: 'POST',
body: JSON.stringify({
nom: this.nom,
prenom: this.prenom,
adresse: this.adresse,
email: this.email
}),
headers: {"Content-Type": "application/json"}
})
.then(this.getUsers)
.catch(err => console.error(err))
this.setState({newUserModal:false});
console.log(this.newUserData) // return undefined
}
toggleNewUserModal = () => {
this.setState({
newUserModal: ! this.state.newUserModal
});
}
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const app = express();
// Connection Mysql
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbusers',
});
connection.connect(err => {
if (err) {
console.log("conection error");
return err;
}
});
// Connection Express Body-Parser Cors
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello from the users server')
});
// Selectionner Tous Les Utilisateurs
app.get('/users', (req, res) => {
const selectQuery = 'SELECT * FROM userslist';
connection.query(selectQuery, (err, results) => {
if(err) {
res.send(err)
}
else {
res.json({data: results})
}
});
});
// Ajouter Un Nouveau Utilisateur
app.post('/users/add', (req, res) => {
let nom = req.body.nom;
let prenom = req.body.prenom;
let adresse = req.body.adresse;
let email = req.body.email;
let insertQuery ="INSERT INTO userslist SET ?"
const user={nom,adresse,prenom,email}
connection.query(insertQuery,user, (err, results) => {
if(err) {
console.log("insert error");
res.send(err)
}
else {
res.send({ error: false, data: results, message: 'user has been
updated successfully.' });
}
});
});
// Editer Un Nouveau Utilisateur
app.post('/users/update/:id', (req, res) => {
let id = req.params.id;
let nom = req.body.nom;
let prenom = req.body.prenom;
let adresse = req.body.adresse;
let email = req.body.email;
let updateQuery =`UPDATE userslist SET ? WHERE id=${id}`
const user={nom,adresse,prenom,email}
connection.query(updateQuery,user, (err, results) => {
if(err) {
console.log("insert error");
res.send(err)
}
else {
res.send({ error: false, data: results, message: 'user has been
updated successfully.' });
}
});
});
// Suprimer un Utilisateur
app.post("/users/delete/:id", (req, res) => {
let id = req.params.id;
let sql = 'DELETE FROM userslist WHERE id=?';
connection.query(sql, [id], (error, results, fields) => {
if (error)
console.error(error.message);
console.log("Deleted Row(s):", results.affectedRows);
res.json({error:false,data: results})
});
});
app.listen(4000, () => {
console.log('Users server worked on port 4000...')
});