Express and mysql. rows are undefined - mysql

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

Related

How can I separate an API into diferent files? (routes) Node.js + MySQL

I'm new here. I wanted to know how can I "separate" mi app.js (API) into several files, mainly for the routes but also the connections too if it is posible. I tried several video tutorials but none of them worked, so here is my code (only file), I want the routes in a separated file (routes.js):
const mysql = require('mysql')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 3050
const app = express()
app.use(bodyParser.json())
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'shop'
})
app.get('/', (req, res) => {
res.send('Welcome to my API!')
})
//ROUTES!!!
app.get('/customers', (req, res) => {
const sql = 'SELECT * FROM customers'
connection.query(sql, (err, results) => {
if (err) throw err
if (results.length > 0) {
res.json(results)
} else {
res.send('No results!')
}
})
})
app.get('/customers/:id', (req, res) => {
const { id } = req.params
const sql = `SELECT * FROM customers WHERE id = ${id}`
connection.query(sql, (err, result) => {
if (err) throw err
if (result.length > 0) {
res.json(result)
} else {
res.send('No result!')
}
})
})
connection.connect(error => {
if (error) throw error
console.log('Database server running!')
})
app.listen(PORT, () => console.log(`Server running on ${PORT}`))
You can use express.Router object to define some routes in separe file. Then export the router object and do app.use('/api/some-sub-path', router)
You can read more about Router here https://expressjs.com/en/guide/routing.html
Also I advice you to read this article https://dev.to/santypk4/bulletproof-node-js-project-architecture-4epf
create n new file ApiRouter.js and add following code in it.
const express = require("express");
const router = express.Router();
router.get('/customers', (req, res) => {
const sql = 'SELECT * FROM customers'
connection.query(sql, (err, results) => {
if (err) throw err
if (results.length > 0) {
res.json(results)
} else {
res.send('No results!')
}
})
})
router.get('/customers/:id', (req, res) => {
const { id } = req.params
const sql = `SELECT * FROM customers WHERE id = ${id}`
connection.query(sql, (err, result) => {
if (err) throw err
if (result.length > 0) {
res.json(result)
} else {
res.send('No result!')
}
})
})
module.exports = router;
//now go to app.js file and add these line of codes below
app.use(bodyParser.json())
const route = require('./path/ApiRouter.js'); // require from file
app.use('/', route);
Create router in another file by:
const router = require('express').Router;
router.get();
And now in app.js use router as
app.use('/' , router);

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

Receive data from multiple tables [Nodejs,MySQL]

What do I need to do to get data from multiple tables?
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '',
user : '',
password : '',
database : ''
});
connection.connect(function(){
console.log("MySQL Database is Connected");
});
app.use(express.static(__dirname + '/css'));
app.use(express.static(__dirname + '/js'));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.get('/',function(req,res){
res.render('index.html');
});
app.get('/load',function(req,res){
connection.query("select * from terms WHERE status = 1",
function(err,rows,fields){
if(err) throw err;
res.end(JSON.stringify(rows));
});
});
app.listen(7001,function(){
console.log("App is started at PORT 7001");
});
With this I can only get data from the terms table. But I need to get data from the impTerms table.
How do I get this?
Thank you
Use sql join in query , has nothing to do with node js.
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT terms.id, terms.name FROM terms JOIN impTerms ON impTerms.id= terms.id and terms.status=1";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
There are several ways you can do,
Passing two sql queries to connection
Var sqlQuery = "select * from terms WHERE status = 1;select * from impTerms";
connection.query(sqlQuery,
function(err,rows,fields){
if(err) throw err;
res.end(JSON.stringify(rows));
});
Output:
[
[], // array of object for terms
[] // array of object for impTerms
]
Changing select query
Var sqlQuery = "select a.*, b.* from a.terms, b.impTerms";
connection.query(sqlQuery,
function(err,rows,fields){
if(err) throw err;
res.end(JSON.stringify(rows));
});

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

NodeJS Output user in browser

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.