How can I display data in mysql in web page? - mysql

I am using nodejs and mysql to display several words in database in webpage with express.
I recently noticed that if I use SELECT inside of async/await, I can only use that data inside of it.
Therefore, I tried to do writeHead inside that function, but did not work.
Below is my code segments.
Could you please give me some advice?
const mysql = require('mysql2/promise');
const getData = async (lang, word) => {
try {
// db connection
var connection = await mysql.createConnection({
host: "-----",
user: "-----",
password: "-----",
database: "-----",
});
var [idA, fieldsA] = await connection.query(`SELECT id FROM en WHERE word=${"'"+word+"'"}`);
var [idB, fieldsB] = await connection.query(`SELECT id FROM ${lang} WHERE word=${"'"+word+"'"}`);
if(idA[0] === undefined && idB === undefined){
return null;
}else{
if(idB[0] === undefined) wordId = idA[0].id;
else wordId = idB[0].id;
var [dataA, fieldsA] = await connection.query(`SELECT * FROM en WHERE id=${"'"+wordId+"'"}`);
var [dataB, fieldsB] = await connection.query(`SELECT * FROM ${lang} WHERE id=${"'"+wordId+"'"}`);
if(lang === 'en' || dataB[0] === undefined){
[dataB, fieldsB] = await connection.query(`SELECT * FROM en WHERE id='null'`);
}
var data = [
{'id': dataA[0].id, 'word': dataA[0].word, 'def': dataA[0].def, 'syn': dataA[0].syn, 'ref': dataA[0].ref, 'area': dataA[0].area},
{'id': dataB[0].id, 'word': dataB[0].word, 'def': dataB[0].def, 'syn': dataB[0].syn, 'ref': dataB[0].ref, 'area': dataB[0].area}
];
return data;
}
} catch (error) {
console.log(error);
}
};
app.get('/search/:lang/:word', (req, res) => {
getData(req.params.lang, req.params.word)
.then((response) => {
console.log(response)
let page = templateSearch.getPage(response, req.params.lang, req.params.word);
res.writeHead(200);
res.end(page);
});
});

Related

How to Send Same Data in Two Database Using Message Broker in Node Js

I want to Send Same Data in Two Database Using Any Message Broker in Node Js
but i don`t understand how to send same data into two database please give proper solution.
I am using MQTT Broker
Broker code
var mosca = require('mosca');
var settings = { port: 1883}
var broker = new mosca.Server(settings)
var mysql = require('mysql');
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root#123',
database: 'abc'
});
db.connect(() => {
console.log("db connect");
})
broker.on('ready', () => {
console.log("broker is ready");
})
broker.on('published', (packet) => {
message = packet.payload.toString()
time = packet.payload.toString()
add = packet.payload.toString()
console.log(message);
if (message.slice(0, 1) != '{' && message.slice(0, 4) != 'mqtt') {
// var dbSet = 'insert into mqttjs set ?'
var dbSet =`INSERT INTO mqttjs (message, time, add) VALUES ("a","b", "c")`;
// var data = {
// message: message
// }
db.query(dbSet, (error, output) => {
if (error) {
console.log(error);
} else {
console.log("data saved");
}
})
}
})
subcriber
This is subscriber code
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.0.92')
client.on('connect', function () {
client.subscribe('myTopic')
})
client.on('message', function (topic, message) {
context = message.toString();
console.log(context)
})
pulisher
This is publisher code
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://192.168.0.92');
client.on('connect', function () {
setInterval(function() {
client.publish('myTopic', 'Hello mqtt');
console.log('Message Sent');
}, 5000);
});

Foreach loop in nodejs

My Project uses Node JS + My SQL
I am running a simple query that checks whether entries exist in database for some params.
If they exist, it then updates them, else it inserts them.
The problem is, it is entering the last entry n times instead of each being unique.
When updating also, it is not able to identify the right row.
router.post('/feeRegister', asyncMiddleware( async(req, res) => {
let post= {
...........
}
JSON.parse(req.body.fees).forEach((i,index) => {
let sql = `SELECT id, period, amount FROM feeregister WHERE schoolId = '${req.body.schoolId}' AND studentId = '${req.body.student}' AND classes = '${req.body.classes}' AND year = '${req.body.year}' AND type = '${JSON.parse(req.body.fees)[index][1]}';`
pool.query(sql, async(err, results) => {
try{
if(err){ throw err }
if(results){
if(results.length){
console.log('Entry Exists', index, results[0].id)
let post2= {
...............
}
let sql2 = `UPDATE feeregister SET ? WHERE id = '${results[0].id}'`;
pool.query(sql2, post2, async(err, results) => {
try{
if(err){ throw err }
if(results){}
}catch(e){ func.logError(e); res.status(500); return; }
})
}else{
console.log('Entry does not exist', index)
let sql = `INSERT INTO feeregister SET ?`
pool.query(sql, post, async(err, results) => {
try{
if(err){ throw err }
if(results){}
}catch(e){ func.logError(e); res.status(500); return; }
})
}
}
}catch(e){ func.logError(e); res.status(500); return; }
})
});
}))
Iam connecting to database like :
var mysql = require('mysql')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'dBName',
password: '',
multipleStatements: true
});
module.exports = pool;
Perhaps you should call the query function with async-await method.
router.post('/feeRegister', asyncMiddleware( async(req, res) => {
let post= {
//
}
JSON.parse(req.body.fees).forEach(async (i,index) => {
let sql = `SELECT id, period, amount FROM feeregister WHERE schoolId = '${req.body.schoolId}' AND studentId = '${req.body.student}' AND classes = '${req.body.classes}' AND year = '${req.body.year}' AND type = '${JSON.parse(req.body.fees)[index][1]}';`
const promisePool = pool.promise();
let results = await promisePool.query(sql);
if(results){
if(results.length){
console.log('Entry Exists', index, results[0].id)
let post2= {
//
}
let sql2 = `UPDATE feeregister SET ? WHERE id = '${results[0].id}'`;
await promisePool.query(sql2);
}else{
console.log('Entry does not exist', index)
let sql = `INSERT INTO feeregister SET ?`
await promisePool.query(sql);
}
}
});}));

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;

Node unhandel promises and imports oop

My code have an obj name SQLFeeter that need to do the sql interaction which get the data post it and pass it along I have some problem which is one imports. The babel doesn't work second while I try to get the data and pass it
const express = require('express');
const router = express.Router();
const mysql = require('mysql')
/*
--------------------------------------
This will handel all get requests
--------------------------------------
*/
/*
//sqlInteractuin test
const SqlDataGetter = require('../../sqlInteraction/GetData');
//import SqlDataGetter from "./sqlInteraction/GetData";
let SqlGetter = new SqlDataGetter
*/
class SqlDataGetter {
constructor()
{
this.con = mysql.createConnection({
host: "localhost",
user: "XXX",
password: "XXX",
database: "APP"
});
}
GetClients()
{
let con = mysql.createConnection({
host: "localhost",
user: "XXX",
password: "AAA",
database: "APP"
});
let resultFromSql = null;
con.connect(function(err) {
if (err) throw err;
let sql_query = "SELECT * FROM contacts"
con.query(sql_query , function (err, result, fields) {
if (err) throw err;
//console.log(fields);
console.log(result);
resultFromSql = result;
});
return resultFromSql;
});
}
Tester()
{
//return this.con
//console.log(this.con)
return 'hello world'
}
}
router.get('/' , async (req , res) =>
{
//Need to make an obj that take the data and do all the querys
res.status(200).send("DataBack");
});
router.get('/Clients' , async (req , res) =>
{
let sql_getter = new SqlDataGetter();
const Clients = sql_getter.GetClients();
console.log(Clients);
SqlDataGetter.GetClients()
res.status(200);
res.send({ respond : Clients});
});
While I am trying to run this at first it works on stand alone but when I create the ajax request it saying GetClients is not a function. And when I try to make the connection to be a property of this object as this.con when I activate this.con.query undifend property query of undifend.
If you use promise-mysql instead of mysql then you'll get promises from the method calls, which will make it easier to work with:
const mysql = require('promise-mysql');
Then your class would look like this:
class SqlDataGetter {
constructor() {
this.conPromise = mysql.createConnection({
host: "localhost",
user: "XXX",
password: "XXX",
database: "APP"
});
}
async GetClients() {
const con = await this.conPromise;
const result = await con.query("SELECT * FROM contacts");
console.log(result);
return result;
}
}
Finally, you'd use that class as follows:
router.get('/Clients' , async (req , res) => {
let sql_getter = new SqlDataGetter();
const clients = await sql_getter.GetClients();
console.log(clients);
res.status(200);
res.send({ respond : clients});
});

Cannot read property 'id' of undefined. Express

The full code is following - pretty simply i wanna add, delete or update posts - when i do one of the things by them self it works but togther it breaks
Iv'd searched alot in the NodeJS MySQL which i use to query the database
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : 3306,
database: 'nodeproject',
user : 'noderoot',
password : 'default'
});
var express = require('express');
var http = require('http');
var path = require('path');
var exphbs = require('express3-handlebars');
var qs = require('querystring');
var app = express();
app.set('port', process.env.PORT || 8000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
configQuery = function() {
connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
}
index = function(req, res){
/*connection.connect(function(err){
if(err != null) {
res.end('Error connecting to mysql:' + err+'\n');
}
});*/
connection.query("SELECT * FROM posts", function(err, rows){
if(err != null) {
res.end("Query error:" + err);
} else {
var myOuterRows = [];
for (var i = 0; i < rows.length; i++) {
var myRows = rows[i];
myOuterRows.push(myRows);
};
res.render('index', {
title: 'Express Handlebars Test',
posts: myOuterRows
});
}
});
};
addpost = function(req, res) {
var post = {
id: req.body.post.id,
postTitle: req.body.post.postTitle,
postContent: req.body.post.postContent,
published: req.body.post.published
};
connection.query('INSERT INTO posts SET ?', post, function(err, result) {
console.log("Neat! you entered a post");
});
res.redirect("/");
}
editpost = function(req, res) {
configQuery();
var edit = {
id: req.body.editpost.id,
postTitle: req.body.editpost.postTitle,
postContent: req.body.editpost.postContent
};
var queryTitle = connection.query("UPDATE posts SET ?", edit, function(err, result) {
console.log("Neat! you editted a post")
});
res.redirect("/");
}
deletepost = function(req, res) {
configQuery();
var deleteThis = {
id: req.body.deletepost.id
};
console.log(deleteThis);
var queryDelete = connection.query("DELETE FROM posts WHERE id = :id", {
id: deleteThis.id
});
res.redirect("/");
}
app.get('/', index);
app.post('/', addpost);
app.post('/', editpost);
app.post('/', deletepost);
//app.get('/list', list);
http.createServer(app).listen(8000, function(){
console.log('Express server listening on port ' + app.get('port'));
});
The error i get is following:
500 TypeError: Cannot read property 'id' of undefined
at editpost (C:\dev\ExpressHbsMysql\app.js:96:24)
at callbacks (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:164:37)
at param (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:138:11)
at pass (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:173:5)
at Object.router (C:\dev\ExpressHbsMysql\node_modules\express\lib\router\index.js:33:10)
at next (C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at Object.methodOverride [as handle] (C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\middleware\methodOverride.js:48:5)
at next (C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\proto.js:193:15)
at C:\dev\ExpressHbsMysql\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:83:7
Where should it go?
app.post('/', addpost);
app.post('/', editpost);
app.post('/', deletepost);
To addpost or to editpost or to deletepost
As far as i can tell from your code i suggest you keep different urls for each handler that way you will tell which handler to call, right now all your post requests call first handler which is addpost
Map your handlers like this
app.post('/post/add', addpost);
app.post('/post/edit', editpost);
app.post('/post/delete', deletepost);
Next in your forms or if your are using ajax post your addrequest to '/post/add', editrequest to /post/edit and so on.