NodeJS Output user in browser - mysql

I made a project where i include database which i wrote on mysql and it make a json file from database and also output all users in browser but I have some problem. I want to output one user how can i do this(this is example how it must output http://localhost:8080/user/1). I used express and mysql. Please help me. Thanks.
This is my code:
'use strict';
const mysql = require('mysql');
const express = require('express');
const http = require('http');
const router = express()
// http://nodejs.org/docs/v0.6.5/api/fs.html#fs.writeFile
const fs = require('fs');
const connection = mysql.createConnection({
host: 'localhost',
user: 'lado',
password: '1234'
});
connection.connect();
connection.query('SELECT * FROM bankdb.account;', function(err, results, fields) {
if(err) throw err;
fs.writeFile('account.json', JSON.stringify(results), function (err) {
if (err) throw err;
console.log('Saved!');
});
connection.end();
});
const pool = mysql.createPool({
host: 'localhost',
user: 'lado',
password: '1234',
database: 'bankdb',
charset: 'utf8'
});
var reo ='<html><head><title>Output From MYSQL</title></head><body><h1>Output From MYSQL</h1>{${table}}</body></html>';
function setResHtml(sql, cb){
pool.getConnection((err, con)=>{
if(err) throw err;
con.query(sql, (err, res, cols)=>{
if(err) throw err;
var table =''; //to store html table
//create html table with data from res.
for(var i=0; i<res.length; i++){
table +='<tr><td>' + (i+1) +'</td><td>'+ res[i].name +'</td><td>'+ res[i].address +'</td></tr>';
}
table ='<table border="1"><tr><th>ID</th><th>Name</th><th>Amount</th></tr>'+ table +'</table>';
con.release(); //Done with mysql connection
return cb(table);
});
});
}
const sqll ='SELECT * FROM bankdb.account';
const server = http.createServer((req, res)=>{
setResHtml(sqll, resql=>{
reo = reo.replace('{${table}}', resql);
res.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
res.write(reo, 'utf-8');
res.end();
});
});
server.listen(8080, ()=>{
console.log('Server running at //localhost:8080/');
router.get('/users/:id', function(req, res, next) {
var user = users.getUserById(req.params.id);
res.json(user);
});
exports.getUserById = function(id) {
for (var i = 0; i < users.length; i++) {
if (users[i].id == id) return users[i];
}
};
});

Just get the specific user based on their id:
router.get( '/user/:id', function( req, res ) { // When visiting '/user/:id'
var id = req.params.id; // For example if you visit localhost/user/24 the id will be 24
connection.query('SELECT * FROM bankdb.account WHERE id=' + mysql.escape( id ), function(err, results, fields) {
if(err) throw err;
fs.writeFile('account.json', JSON.stringify(results), function (err) {
if (err) throw err;
console.log('Saved!');
});
connection.end();
});
} );
If you grab every user from the database, your program will use up much more memory.
Just grab the one you need and work with him.

Related

Routing to other url in node.js

I am currently working on a project where I have CRUD operation using node.js and mysql.
var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
var con = mysql.createConnection({
host: "database",
user: "admin",
password: "pass",
database: "db"
});
var app = express();
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM shops where id =33", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
app.use('/shop', function(err) {
con.query("SELECT * FROM shops where id =34", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
app.listen('3000', () => {
console.log('Server started on port 3000');
});
I want to get the shops data using localhost:3000/shops and brands data using localhost:3000/brands. But i don't know how to do that because i am very new in node.js. Infact,Today i my first day. I someone gives me som demo project or some thing like this. I will be very thankful.
app.get('/brands',(req,res) =>{
//inside query
})
like...thiss

Node.js crashes after connecting to mysql database

Basically, node.js will run the function perfectly, and it will continue running for ~10 seconds and then it will simply crash. Below is the full code, because I dont know what part is causing the actual error, but I hope someone will see where i'm messing up.
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
var fs = require('fs');
var mysql = require('mysql');
const path = require('path');
client.on("ready", () => {
console.log('Running...');
});
var con = mysql.createConnection({
host: "",
user: "",
password: "",
database: "",
});
client.on("message", async message => {
if (message.author.bot) return;
if (!message.guild) {
message.reply('Please do not DM the bot.');
return;
};
if (message.content.toLowerCase() == "!script") {
if (message.channel.name != "bot-chat") {
message.author.send('Please only use bot commands in the #bot-chat channel.');
return;
};
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM Users", function (err, result, fields){
if (err) throw err;
result.forEach(function(User){
var UserDiscord = User.DISCORD;
var UserKey = User.SKEY;
if (usr_dc == message.author.username+"#"+message.author.discriminator) {
message.author.sendCode("php",usr_key)
.then()
.catch(console.log);
if (message.guild.name == "Towlie Boi") {
message.author.sendCode("lua",`_G.key='KeyHere'
loadstring(game:HttpGet("https://basehosting.xyz/sCrIpT1"))()`)
.then()
.catch(console.log);
message.channel.send('Script has been sent to your DMs, If you did not receive a DM then you have not allowed the bot to send you DMs');
.then()
.catch(console.log);
};
};
});
});
});
} else if (message.channel.name == 'whitelist') {
if (message.content.substring(0,3).toLowerCase() == '!wl') {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM Keys", function(err, result, fields) {
if (err) throw err;
result.forEach(function(Key) {
var key = Key.Code;
if (message.content.substring(4) == key) {
var query = "DELETE FROM `Keys` WHERE `Keys`.`Code` = \'"+message.content.substring(4)+"\'";
con.query(query, function(err) {
if (err) throw err;
con.query("INSERT INTO `Users` (`DISCORD`, `SKEY`, `IP`) VALUES ('"+message.author.username+"#"+message.author.discriminator+"', '"+message.content.substring(4)+"', '');", function(err) {
if (err) throw err;
message.reply('Whitelisted Succesfully');
return;
});
});
};
});
});
});
};
};
};
client.login(config.token);
I cant really see a error, as i've just begun coding for node.js and dont know much about javascript, I thought I maybe had to close the connection after I queued the data, but that didnt seem to work either. Thanks for any answers :)
How about connecting database connection from a separate file.
module.exports = {
host : 'localhost',
user : 'root',
password : '',
database : 'bookstore',
charset : 'utf8'
}
and passing on controlling.
var database = require('../models/database.js')();

express.js with MySQL

I just started learning node.js...
Here is an example of my code. In this example everything works.
But, I have a question. How to make several SQL queries and send results to template?
At the moment I can only do this for one query...
Thanks.
//connection database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'test'
});
connection.connect(function (err){
if (err) throw err;
console.log('Database connected . . . \n\n');
});
router.get('/', function(req, res, next) {
var sql = 'SELECT * FROM `test`';
connection.query(sql, function(err, rows, field){
if (err) throw err;
res.render('index', {
data: rows
})
});
});
Here is an answer following my comment since you mentioned you couldn't figure it out on your own.
First snippet uses promises, a quick helper function, but no external library. Second snippet uses the external async.js library and is a bit more callback-heavy. Both of them tackle the problem assuming we want the queries to be executed in parallel.
With promises
router.get('/', async function(req, res, next) {
var queries = ['SELECT * FROM `test`',
'SELECT * FROM `test2`',
'SELECT * FROM `test3`'];
var allResults = [];
/*transform our `query` array into an array of promises, then
await the parallel resolution of all the promises*/
var allQueryRows = await Promise.all(queries.map(query => promiseQuery(query)));
/*'allQueryRows' is an array of rows, so we push each of those
into our results*/
allQueryRows.forEach(function(rows){
allResults.push(...rows);
});
res.render('index', {
data: allResults
})
});
function promiseQuery(sqlQuery){
return new Promise((resolve, reject) => {
connection.query(sqlQuery, function(err, rows, field){
if(err)
return reject(err);
resolve(rows);
})
})
}
With callbacks and async.js
const async = require('async');
router.get('/', function(req, res, next) {
var queries = ['SELECT * FROM `test`',
'SELECT * FROM `test2`',
'SELECT * FROM `test3`'];
var allResults = [];
async.each(queries, function(sqlQuery, callback){
connection.query(sqlQuery, function(err, rows, field){
if(err)
throw err;
allResults.push(...rows);
callback();
});
}, function(){
res.render('index', {
data: allResults
});
});
});

If I console.log my results it shows up, but if I return it it doesn't

My return result doesn't make it all the way back to API endpoint.
Do you see what I'm doing wrong?
app.js
const express = require('express');
const app = express();
app.use(express.static('client'));
var GetContracts = require('./contractsService');
app.get('/contracts', async (req, res) => {
var results = await GetContracts.get();
console.log(results);
res.send(results);
});
module.exports = app;
contractsService.js
var mysql = require('mysql');
const config = require('./config')
var con = mysql.createConnection({
host: config.HOST,
user: config.USER,
password: config.PASSWORD,
database: config.DATABASE
});
exports.get = function () {
con.connect(function (err) {
if (err) {
throw new Error('Error by Rodney')
};
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) {
throw new Error('Error by Rodney')
};
return result;
//console.log(result); //works
});
});
}
query method accepts error-first callback that isn't affected by returned value. GetContracts.get doesn't return a promise, and awaiting won't do anything.
It should be promisified in order to be used in promise control flow:
exports.get = function () {
return new Promise((resolve, reject) => {
con.connect(function (err) {
if (err) {
reject(new Error('Error by Rodney'))
};
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) {
reject(new Error('Error by Rodney'));
} else
resolve(result);
});
});
});
}
Or preferably, use existing promise-based MySQL library like promise-mysql, something like:
var mysql = require('promise-mysql');
const conPromise = mysql.createConnection({
host: config.HOST,
user: config.USER,
password: config.PASSWORD,
database: config.DATABASE
});
exports.get = async () => {
const con = await conPromise;
const result = await con.query("SELECT * FROM " + config.DATABASE + ".Contracts");
return result;
};

Express and mysql. rows are undefined

This is my code. I am writing API and I want to send information about products that client has input.
const express = require('express');
const mysql = require('mysql');
const morgan = require('morgan');
const app = express();
app.use(morgan('short'));
app.use(express.static('./public'));
// app.get('/', (req, res, next)=>{
// res.send('Hello World');
// });
function getConnection(){
return mysql.createConnection({
host: 'localhost',
user: 'root',
password:'samsung793',
database: 'demo2'
})
}
app.get('/models/:id', (req, res, next)=>{
console.log('Fetching id ' + req.params.id);
const connection = getConnection();
const queryStr = 'SELECT * FROM products WHERE id=?'
const modelId = req.params.id;
connection.query( queryStr, [modelId], (err, rows, fields)=>{
if (err){
res.send('<h1>500 bad request</h1> Error! Sorry for error, we are working on it!');
res.sendStatus(500);
return;
//throw err;
}
console.log('Ready');
res.json(rows);
})
// res.end();
})
app.get('/:name', (req, res, next)=>{
console.log('Fetching name ' + req.params.name);
const connection = getConnection();
const queryStr = `SELECT * FROM products WHERE MATCH(name) AGAINST(${req.params.name}, in natural language)`
const modelName = req.params.name;
connection.query( queryStr, [modelName], (err, rows, fields)=>{
if (err){
res.send('<h1>500 bad request</h1> <h3>Error!</h3> <h4>Sorry for error, we are working on it!</h4>');
res.sendStatus(500);
return;
//throw err;
}
console.log('Ready');
res.json(rows);
console.log(rows);
})
// res.end();
})
app.listen(3000, ()=>{
console.log('server is listening on port 3000');
} )
when I log to console the rows, it is undefined. How can I fix it? What is the problem?
Sorry for first post. I edit and add all code now. Please help me to solve this problem.
You need to check if any error occur while querying
app.get('/:name', (req, res, next) => {
console.log('Fetching name ' + req.params.name);
const connection = getConnection();
const queryStr = 'SELECT * FROM products WHERE MATCH(name) AGAINST(?, in natural language mode)';
const modelName = req.params.name;
connection.query( queryStr, [modelName], (err, rows, fields)=>{
console.log('Ready');
if(err) {
console.log(err);
return res.status(500).send(err);
}
console.log(rows);
res.json(rows);
})
})
If you are using prepared statement, you do not need to pass ${req.params.name}, just pass ?
Thank you for answers. I write code here in case someone needs it.
It works this way:
app.get('/:name', (req, res, next)=>{
console.log('Fetching name ' + req.params.name);
const connection = getConnection();
const queryStr = `SELECT * FROM products WHERE MATCH(name, url) AGAINST(? IN NATURAL LANGUAGE MODE) `
const modelName = req.params.name;
connection.query( queryStr, modelName, (err, rows, fields)=>{
console.log(rows);
if (err){
res.status(404).send(" Something went wrong");
// res.sendStatus(500);
throw err;
}
console.log('Ready');
res.json(rows);
})
// res.end();
})