How do I pass mysql database content to a different page? - mysql

I am trying to display my database content to an ejs web page. However, I am running into a problem when trying to pass the content between pages.
I have a JavaScript page "store.js" which has the server running:
store.js-
var express = require('express');
var dbcon = require('./app/db/databaseconnection');
//var path = require('path');
//dbcon.connection;
var app = express();
var router = express.Router();
dbcon.connect();
console.log(dbcon.getproducts());
//var filepath = path.join(__dirname, '../../views/')
var filepath = __dirname + '/views/';
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use('/', router);
router.get('/', (request, response) => response.render(filepath + 'index', { page_name: 'home' }));
router.get('/store', (request, response) => response.render(filepath + 'store', { page_name: 'store' }));
router.get('/about', (request, response) => response.render(filepath + 'about', { page_name: 'about' }));
router.get('/contact', (request, response) => response.render(filepath + 'contact', { page_name: 'contact' }));
router.get('/build', (request, response) => response.render(filepath + 'build/build'));
router.get('/learn', (request, response) => response.render(filepath + 'learn/learn'));
app.use('*', (request, response) => response.render(filepath + '404', { page_name: '404' }));
app.listen(3000, () => console.log("Server running at Port 3000"));
Then I have a JavaScript page which includes the database connection:
databaseconnection.js-
var mysql = require('mysql');
var connection = mysql.createConnection(conObject = {
host: "localhost",
user: "root",
password: "LOTOS123l",
database: "dbComputerStore"
});
module.exports = {
connect: () =>
{
connection.connect((error) => {
if (error) throw error;
console.log(conObject.database + " connected!");
});
},
// The display method prints the returned result to the console.
// Change this to return the result. Maybe a toString() ?
getproducts: () => {
/*var result = */connection.query('SELECT * FROM products', (error, result) => {
return result;
//return result;
// console.log(result);
// How to get certain properties
// console.log(result[0].brand);
// console.log(result[0].series);
// console.log(result[0].model);
});
//return result.result;
},
createdb: () => {
},
createtable: () => {
},
populatetable: () => {
}
}
So on the store.js page I have the console.log(dbcon.getproducts()); Which I was hoping would display the database content of the "products" table. However I keep getting undefined. Basically, I can't get it to pass from the database connection page to the store.js page.
If I get this to work, my next step would be to find a way to display the products table to an ejs page. I've been trying to solve this for a while now so any help would be appreciated! Thank You!

Following up my comments, here's how you can modify databaseconnection.js module to use a connection pool and return query results via Promises:
Note: the code is mostly untested
const mysql = require("mysql");
const pool = mysql.createPool({
connectionLimit: 10, // adjust this according to your needs
host: "localhost",
user: "root",
password: "LOTOS123l",
database: "dbComputerStore"
});
module.exports = {
// you don't need the connect method anymore
getProducts: () => new Promise((resolve, reject) => {
pool.query("SELECT * FROM products", (error, results, fields) => {
if (error) {
reject(error);
} else {
resolve(results);
}
});
}),
// ...
};
then in store.js, you can do:
const dbcon = require('./app/db/databaseconnection');
dbcon.getProducts()
.then(results => {
console.log(results);
})
.catch(err => {
console.error(err);
});
// or you could use async/await syntax:
const asyncFn = async () => {
try {
const results = await dbcon.getProducts();
console.log(results);
} catch (ex) {
console.error(err);
}
};
asyncFn();

Related

Getting empty {} from mysql table, on React and node.js

For some reason am getting empty object back from mysql table, the table is filled in with some vacation detail. And i want to display them with map in my react app.
On the client side am doing the request with useEffect state and axios.
useEffect(() => {
axios.get("http://localhost:3001/vacations")
.then((response) => {
let vacationsResponse = response.data;
dispatch({ type: ActionType.GetAllVacations, payload: vacationsResponse })
}).catch(err => {
console.log("Failed to get data" + err)
})
}, [dispatch])
this is the server side:
const vacationsControllers = require("./Controllers/vacationsControllers");
const cors = require("cors");
server.use(cors({ origin: "http://localhost:3000" }));
server.use("/users", usersController);
server.use("/vacations", vacationsControllers);
server.listen(3001, () => console.log("Listening on http://localhost:3001"));
this is the vacationsControllers folder:
router.get("/", async (request, response) => {
let vacationsData = request.body;
try {
await vacationsDao.getAllVacations(vacationsData);
response.json();
console.log(vacationsData) *get this empty in the node terminal*
} catch (e) {
console.error(e);
response.status(600).json();
}
});
module.exports = router;
The sql execute (the vacationDao folder):
let connection = require("./connection-wrapper");
async function getAllVacations(vacationsData) {
const sql = `SELECT * FROM current_deals`;
await connection.executeWithParameters(sql);
return vacationsData;
}
module.exports = {
getAllVacations,
};

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;

How can I resolve a promised mysql query in express.js?

I'm trying to use the npm package promise-mysql and return json data (or a string doesn't matter) but I'm having issues following the promise chain with await/async.
With the current code i'm receiving Promise { undefined } in the console.log I have right before the response to the user. The response just sends nothing to the user and closes it. Can anyone point in the right direction of how to debug this?
index.js
app.get("/", async (req, res) => {
console.log( Promise.resolve(await getLogs()) )
res.send(await getLogs());
});
mysql.js
const mysql = require("promise-mysql");
let pool;
async function startDatabasePool() {
pool = await mysql.createPool({
connectionLimit: 10,
host: "xxx",
user: "xxx",
password: "xxx",
database: "xxx"
});
}
async function getDatabasePool() {
if (!pool) await startDatabasePool();
return pool;
}
module.exports = {
getDatabasePool,
startDatabasePool
};
users.js
const { getDatabasePool } = require("./mysql");
async function getLogs() {
let pool = await getDatabasePool();
pool.query("SELECT * from logs order by logdate desc", function(
error,
results,
fields
) {
if (error) throw error;
return JSON.stringify(results);
});
}
module.exports = {
getLogs
};
index.js
app.get("/", async (req, res) => {
const result = await getLogs();
res.send(result);
});
mysql.js
const mysql = require("promise-mysql");
let pool;
module.exports.startDatabasePool = async () => {
pool = await mysql.createPool({
connectionLimit: 10,
host: "xxx",
user: "xxx",
password: "xxx",
database: "xxx"
});
}
module.exports.getDatabasePool = async () => {
if (!pool) await startDatabasePool();
return pool;
}
// convert function as promise
module.exports.executeQuery = async(params) => {
return new Promise((resolve, reject) => {
pool.query(params, function (error, result, fields) {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
};
users.js
const { executeQuery } = require("./mysql");
module.exports.getLogs = async () => {
return await executeQuery("SELECT * from logs order by logdate desc");
}
First I'd try it like:
app.get("/", async (req, res) => {
let logs = await getLogs()
console.log(logs)
res.send(logs);
});
I hope it helps!

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

Nodejs rest api mysql

I'm trying to display all members from MYSQL database with Node Js. But I get some errors. My database name is apibase and I have table members (id, name, email, phone) My code is below:
//routes.js file
const pool = require('../data/config');
const router = app => {
app.get('/', (request, response) => {
response.send({
message: 'Welcome to the Node.js Express REST API!'
});
});
// Display all users
app.get('/members', (request, response) => {
pool.query('SELECT * FROM members', (error, result) => {
if (error) throw error;
response.send(result);
});
});
// Display a single user by ID
app.get('/members/:id', (request, response) => {
const id = request.params.id;
pool.query('SELECT * FROM members WHERE id = ?', id, (error, result) => {
if (error) throw error;
response.send(result);
});
});
}
module.exports = router;
And my database.js file:
const mysql = require('mysql');
const config = {
host: 'localhost',
user: 'root',
password: '',
database: 'apibase',
};
const pool = mysql.createPool(config);
module.exports = pool;
And app.js file
const express = require('express');
const port = 8080;
const bodyParser = require('body-parser');
const routes = require('./routes/routes')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
routes(app);
const server = app.listen(port, (error) => {
if (error) return console.log(`Error: ${error}`);
console.log(`Server listening on port ${server.address().port}`);
});
I don't know what is the problem with this code, can somebody help me with this.