Why the server not accessing connection variable? - javascript

I'm trying to retrieve data from database using Node.js restify framework. The server is running fine but when I visit http://localhost:8081/get I get this error:
{
"code": "InternalError",
"message": "connectionPool is not defined"
}
Here's my code:
server.js
require('./app/core/routes.js');
routes.js
var restify=require('restify');
var fs=require('fs');
var controllers = {};
controllers_path = process.cwd() + '/app/controllers';
fs.readdirSync(controllers_path).forEach(function (file) {
if (file.indexOf('.js') != -1) {
controllers[file.split('.')[0]] = require(controllers_path + '/' + file);
}
});
var server=restify.createServer();
server.get('/get', controllers.article.printHello);
server.listen(8081, function (err) {
if (err)
console.error(err);
else
console.log('App is ready at : ' + 8081);
});
article.js
var something2=require('../core/connection.js');
something2.something();
exports.printHello= function(req, res, next){
connectionPool.getConnection(function (err, connection) {
if (err) {
res.send({
Error: err,
Message: "Can't connect Database."
});
} else {
//queries
connection.query("SELECT * FROM book", function (err, rows, fields) {
res.send({
json: rows
});
});
}
});
};
connection.js
var mysql = require('mysql');
exports.something = function () {
var connectionPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'books'
});
}

In your connection.js file, export the pool
var mysql = require('mysql');
exports.connectionPool = function() {
return mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'books'
});
}
Then use it in your article.js file
var conn = require('../core/connection.js');
var pool = conn.connectionPool();
exports.printHello = function(req, res, next){
pool.getConnection(function (err, connection) {
if (err) { ...

You have to return your variable connectionPool in your connection.js's something function.
connection.js
var mysql = require('mysql');
exports.something = function () {
var connectionPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'books'
});
return connectionPool; // notice here
}
article.js
var something2=require('../core/connection.js');
var connectionPool = something2.something(); //notice here
exports.printHello= function(req, res, next){
connectionPool.getConnection(function (err, connection) {
if (err) {
res.send({
Error: err,
Message: "Can't connect Database."
});
} else {
//queries
connection.query("SELECT * FROM book", function (err, rows, fields) {
res.send({
json: rows
});
});
}
});
};

Related

How to merge two files API (Node.js)

I am a node.js and MySQL beginner and I just started setting up and trying out some basic code.
I find these two APIs to practice, one is the API for the CRUD database, and the other is the API for judging user login / registration.I tried to merge the APIs of these two files, and the result was a problem. I think the current problem is the configuration file (conf.js).I plan to write a function and then wrap any file and use it again, so that the configuration files may not conflict, but I don’t know how to start.
These are the two API teaching URLs I practiced
http://www.expertphp.in/article/user-login-and-registration-using-nodejs-and-mysql-with-example
https://www.footmark.info/programming-language/nodejs/nodejs-restful-webapi-mysql/
index.js
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var authenticateController = require("./controllers/authenticate-controller");
var registerController = require("./controllers/register-controller");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/api/register", registerController.register);
app.post("/api/authenticate", authenticateController.authenticate);
app.listen(3000);
app.js
var bodyparser = require("body-parser");
var express = require("express");
var conf = require("./conf");
var functions = require("./functions");
var user = require("./routes/user");
var app = express();
req.body
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
//app.use(functions.passwdCrypto);
app.use("/user", user);
app.listen(conf.port, function() {
console.log("app listening on port " + conf.port + "!");
});
authenticate-controller.js
var connection = require('./../conf');
module.exports.authenticate=function(req,res){
var email=req.body.email;
var password=req.body.password;
connection.query('SELECT * FROM user WHERE email = ?',[email], function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
if(results.length >0){
if(password==results[0].password){
res.json({
status:true,
message:'successfully authenticated'
})
}else{
res.json({
status:false,
message:"Email and password does not match"
});
}
}
else{
res.json({
status:false,
message:"Email does not exits"
});
}
}
});
}
register-controller.js
var connection = require('../conf');
module.exports.register=function(req,res){
var today = new Date();
var user={
"name":req.body.name,
"email":req.body.email,
"password":req.body.password,
"created_at":today,
"updated_at":today
}
connection.query('INSERT INTO user SET ?',user, function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
res.json({
status:true,
data:results,
message:'user registered sucessfully'
})
}
});
}
user.js(models)
var mysql = require("mysql");
var conf = require("../conf");
var connection = mysql.createConnection(conf.db);
var sql = "";
module.exports = {
items: function(req, callback) {
sql = "SELECT * FROM user";
return connection.query(sql, callback);
},
item: function(req, callback) {
sql = mysql.format("SELECT * FROM user WHERE userId = ?", [req.params.id]);
return connection.query(sql, callback);
},
add: function(req, callback) {
sql = mysql.format("INSERT INTO user SET ?", req.body);
return connection.query(sql, callback);
},
delete: function(req, callback) {
sql = mysql.format("DELETE FROM user WHERE userId = ?", [req.params.id]);
return connection.query(sql, callback);
},
put: function(req, callback) {
connection.beginTransaction(function(err) {
if (err) throw err;
sql = mysql.format("DELETE FROM user WHERE userId = ?", [req.params.id]);
connection.query(sql, function(err, results, fields) {
if (results.affectedRows) {
req.body.id = req.params.id;
sql = mysql.format("INSERT INTO user SET ?", req.body);
connection.query(sql, function(err, results, fields) {
if (err) {
connection.rollback(function() {
callback(err, 400);
});
} else {
connection.commit(function(err) {
if (err) callback(err, 400);
callback(err, 200);
});
}
});
} else {
callback(err, 410);
}
});
});
},
patch: function(req, callback) {
sql = mysql.format("UPDATE user SET ? WHERE userId = ?", [req.body, req.params.id]);
return connection.query(sql, callback);
}
};
user.js(routes)
var express = require("express");
var user = require("../models/user");
var router = express.Router();
router
.route("/")
.get(function(req, res) {
user.items(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.length) {
res.sendStatus(404);
return;
}
res.json(results);
});
})
.post(function(req, res) {
user.add(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
res.status(201).json(results.insertId);
});
});
router
.route("/:id")
.get(function(req, res) {
user.item(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.length) {
res.sendStatus(404);
return;
}
res.json(results);
});
})
.delete(function(req, res) {
user.delete(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.affectedRows) {
res.sendStatus(410);
return;
}
res.sendStatus(204);
});
})
.put(function(req, res) {
user.put(req, function(err, results) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (results === 410) {
res.sendStatus(410);
return;
}
user.item(req, function(err, results, fields) {
res.json(results);
});
});
})
.patch(function(req, res) {
user.patch(req, function(err, results, fields) {
if (err) {
res.sendStatus(500);
return console.error(err);
}
if (!results.affectedRows) {
res.sendStatus(410);
return;
}
req.body.id = req.params.id;
res.json([req.body]);
});
});
module.exports = router;
conf.js
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database: "farmbot",
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports = connection;
/*If I comment out the code below, I can execute the login / register API*/
/*Without commenting out, can only perform CRUD on the database*/
module.exports = {
db: {
host: "localhost",
user: "root",
password: "1234",
database: "farmbot"
},
port: 3000
};
You will have to refactor them properly. You will need only once file to begin with. Why using it twice?
Refactor them in one file instead of listening to them on different ports. Once done, you can show the code to us so that we can fix it further if there's an issue.
Start from index.js and merge app.js with it but a bit carefully. I think doing it by yourself you will learn much from it.

Server side code does not recognize my req.body.variable, stating that it is undefined

Im creating a web application that should send info from the client side to the server side every time a specific button is pressed. When I press the button, the terminal continues to tell me that the value I am trying to pass through the post request body is undefined.
Client side code (Where button is called from) -
function upvote(elem) {
var parentID = elem.parentNode.id;
console.log('Upvote button was clicked' + parentID);
fetch('/upvote', { //This is called to pass the body data to server side code
method: 'post',
body: JSON.stringify({
id: parentID
})
})
.then(function(res) {
if(res.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
}
function downvote(elem){
var parentID = elem.parentNode.id;
console.log('Downvote button was clicked');
fetch('/downvote', { //This is called to pass the body data to server side code
method: 'POST',
body: JSON.stringify({
id: parentID })
})
.then(function(res) {
if(res.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
}
setInterval(function() {
fetch('/ranking', {method: 'GET'})
.then(function(response) {
if(response.ok) return response.json();
throw new Error('Request failed.');
})
.then(function(data) {
})
.catch(function(error) {
console.log(error);
});
}, 1000);
My app.js (Server side code) --
const bodyParser = require('body-parser');
const mysql = require('mysql');
const path = require('path');
const app = express();
const {getLoginPage, login} = require('./routes/index');
const {players, questionsPage, upvoteQues, downvoteQues, ranking, addQuestionsPage, addQuestion, deleteQuestion, editQuestion, editQuestionPage} = require('./routes/question'); //All my routes
const port = 5000;
const db = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '',
database: ''
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
global.db = db;
// configure middleware
app.set('port', process.env.port || port); port
app.set('views', __dirname + '/views'); folder to render our view
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.get('/', getLoginPage);
app.get('/questions', questionsPage);
app.get('/add', addQuestionPage);
app.get('/edit/:id', editQuestionPage);
app.get('/delete/:id', deleteQuestion);
app.get('/ranking', ranking);
app.post('/', login);
app.post('/add', addQuestion);
app.post('/edit/:id', editQuestion);
app.post('/upvote', upvoteQues); //This is then used
app.post('/downvote', downvoteQues); //This is then used
// set the app to listen on the port
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
My question.js (More server side code, just separated into a different file)
const fs = require('fs');
module.exports = {
questionsPage:(req, res) =>{
let query = "SELECT * FROM `Questions` ORDER BY Ranking DESC";
db.query(query, (err, result) => {
if (err) {
console.log('Query error');
res.redirect('/');
}
res.render('questions.ejs', {
title: "JustAsk!",
questions: result,
});
});
},
upvoteQues: (req, res) => {
console.log(req.body.id); //Error here
let updateQuery = "UPDATE `Questions` Ranking = Ranking+1 WHERE QuestionID = '"+ req.body.id + "'" //Error here
db.query(updateQuery, (err, result) => {
if(err){
console.log('Query error');
res.redirect('/players')
}
});
},
downvoteQues: (req, res) =>{
console.log(req.body.id); //Error here
let updateQuery = "UPDATE `Questions` Ranking = Ranking+1 WHERE QuestionID = '"+ req.body.id + "'" //Error here
db.query(updateQuery, (err, result) => {
if(err){
console.log('Query error');
res.redirect('/players')
}
});
},
ranking: (req, res) => {
let query = "SELECT * FROM `Questions` ORDER BY Ranking DESC";
db.query(query, (err, result) => {
if (err) {
console.log('Query error');
}
res.send(result);
});
}
};
The body should be in JSON format, not a string.
body: JSON.stringify({
id: parentID
})
change to:
body: { id: parentID }
and content type should be 'application/json` like below.
fetch('/url', {
method: 'POST',
body: {id: parentID },
headers: {
"Content-Type": "application/json",
}
})

How do you pass and execute a mysql query?

I was wondering how to execute a mysql query so that the client can see like "users registered: number"
Server.js:
var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'root',
database: 'kitsune',
connectionLimit: 50,
port: 3306 });
connection.connect(function(err) {
if (err) throw err;
});
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
module.exports = connection;
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var countQuery = "SELECT Count(ID) AS NumberOfPenguins FROM Penguins"; console.log(countQuery);
connection.query(countQuery, function(err, rows) {
if (err) throw err;
console.log('Connected!');
});
var renderedHtml = ejs.render(content, {countQuery: countQuery});
res.end(renderedHtml);
});
}).listen(80);
index.html:
<html>
<head>
</head>
<body>
Users registered: <%= countQuery %>
</body>
</html>
This only shows the query but it does not execute it. Any idea on how to execute it?
You executed the query sure but you never did anything with the results. The result is the rows passed in the callback function.
connection.query(countQuery, function(err, rows) {
if (err) throw err;
var renderedHtml = ejs.render(content, {countQuery: rows});
res.end(renderedHtml);
});

How to connect to mysql properly in nodejs?

what i trying to do here is query to mysql database, but when i execute my query, it just loading forever, no error untill it timed out, how to solve this? below is my db.js code :
Db.js :
var mysql = require("mysql");
var settings = require("../settings");
exports.executeSql = function (sql, callback) {
var conn = new mysql.createConnection(settings.dbConfig);
conn.connect(function(err){
if(err){
console.log(err + "1");
return;
}
console.log(conn.log + "2");
})
};
and here is my bassCtrl.js :
var db = require("../core/db");
var httpMsgs = require("../core/httpMsgs");
exports.get_user = function(req, resp) {
db.executeSql("select * from mst_user", function(data, err) {
console.log("in controller");
if (err) {
httpMsgs.show500(req, resp, err);
} else {
httpMsgs.sendJson(req, resp, data);
};
});
};
and here is my routes.js
var express = require('express');
var bassCtrl = require("../controllers/bassCtrl");
var httpMsgs = require("../core/httpMsgs");
var jwt = require('jsonwebtoken');
module.exports = function(app, express) {
var router = express();
router.route('/get_user').get(bassCtrl.get_user);
return router;
};
below is my HttpMsgs.js :
var settings = require("../settings");
exports.show500 = function(req, resp, err) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(500, "Internal Error occuared", {"Content-Type":"text/html"});
resp.write("<html><head><title>500</title></head><body>500: Internal Error. Details: " + err + "</body></html>");
} else {
resp.writeHead(500, "Internal Error occuared", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Error occurred: " + err }));
}
resp.end();
}
exports.sendJson = function(req, resp, data) {
resp.writeHead(200, {"Content-Type":"application/json"});
if (data) {
resp.write(JSON.stringify(data));
}
resp.end();
}
exports.show405 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(405, "Method not supported", {"Content-Type":"text/html"});
resp.write("<html><head><title>405</title></head><body>405: Method not supported.</body></html>");
} else {
resp.writeHead(405, "Method not supported", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Method not supported"}));
}
resp.end();
}
exports.show413 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(404, "Resource not found", {"Content-Type":"text/html"});
resp.write("<html><head><title>413</title></head><body>404: Resource not found.</body></html>");
} else {
resp.writeHead(404, "Resource not found", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Resource not found"}));
}
resp.end();
}
exports.show413 = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(413, "Request Entity Too Large", {"Content-Type":"text/html"});
resp.write("<html><head><title>413</title></head><body>413: Request Entity Too Large.</body></html>");
} else {
resp.writeHead(413, "Request Entity Too Large", {"Content-Type":"application/json"});
resp.write(JSON.stringify({ data: "Request Entity Too Large"}));
}
resp.end();
}
exports.send200 = function(req, resp) {
resp.writeHead(200, {"Content-Type":"application/json"});
resp.write(JSON.stringify(
{status: "success", code: 200}
));
resp.end();
}
exports.showHome = function(req, resp) {
if (settings.httpMsgsFormat === 'HTML') {
resp.writeHead(200, {"Content-Type":"text/html"});
resp.write("<html><head><title>200</title></head><body>Your server connected dude ! :)</body></html>");
} else {
resp.writeHead(200, {"Content-Type":"application/json"});
resp.write(JSON.stringify(
{status: "Your server connected dude ! :)"}
));
}
resp.end();
}
and here is my settings.js :
exports.dbConfig = {
user: "root",
password: "",
host: "localhost",
database: "zouk"
};
exports.httpMsgsFormat = "json";
when i trigger localhost:5000/get_user, it just loading till it timed out, and my console.log print this line console.log(connection.log + "2"); with undefined as the value. is there something i missing?
wait a minute, why my question rated minus?
You didn't execute your query in Db.js file, and your code don't call the callback too, that's why it run until timeout.
var connection = mysql.createConnection({
host : ***,
user : ***,
password : ***,
database : ***,
});
connection.connect();
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
//your callback go here.
// callback(rows);//pass whatever you need in.
});
connection.end();
Plus, your controller have no require for httpMsgs. I think it should have.

Why is it showing connection not defined?

I'm trying to use connection from a connection.js file and use it in different file webFrontend.js using exports object. Now what I get on running server is:
{
"Result": "undefinedThis is result"
}
That means connection is not defined. Why is it happening? connection is working fine if getConnection is created in same (webFrontend.js) file, but the problem is when I use getConnection in same exports function in connection.js hence the connection not defined error:
Here are 2 necessary files (routes file has no problem) that explains what I'm doing:
connection.js
var mysql = require('mysql');
exports.connExport = function () {
var connectionPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
if(connectionPool) {
connectionPool.getConnection(function (err, connection) {
if (err) {
return err;
} else {
return connection;
}
});
}else{
var abc="return error";
return abc;
}
}
webFrontend.js
var connObj=require('../Routes/connection.js');
var connection=connObj.connExport();
exports.getIndivRecords= function(req, res, next){
res.send({
Result: connection+"This is result"
});
return next();
};
No need for the .js file extension, it's automagically added for you.
The code below uses standard error-first callbacks
webFrontend.js
var connection = require('../Routes/connection');
exports.getIndivRecords = function(req, res, next){
// connection takes a standard error-first callback
connection(function(err, conn){
if (err) {
// Handle the error returned
console.log(err);
}
// The database connection is available here as conn
console.log( "Connection:" + conn);
// presumably you want to do something here
// before sending the response
res.send({
Result: conn + "This is result"
});
});
return next();
};
connection.js
var mySQL = require('mysql');
var connectionPool = mySQL.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
var getConnection = function (cb) {
connectionPool.getConnection(function (err, connection) {
// pass the error to the callback
if (err) {
return cb(err);
}
cb(null, connection);
});
};
module.exports = getConnection;
First of all #Dan Nagle was right no need of .js
Second You are getting the connection undefinded because still the method doesnt returned with result.
Use promise to call your Connection.js method
Your node is single threaded async execution,
He doest wait for the method to return a result
1) Problem with your javascript is that
var connection=connObj.connExport();
in Creation stage connection was defined by javascript as undefined and as
connObj.connExport(); as still not returned with answer
it executed this function in which connection was undefined
exports.getIndivRecords= function(req, res, next){
res.send({
Result: connection+"This is result"
});
Use promise read this first so you can understand something about promise and callback if you are unable to solve than comment i will play with it.But first you try.Thanku
Understanding promises in node.js
Ok Try This I have used promise here
var connObj = require('../Routes/connection');
connObj.connExport().then(
function (connection) {
exports.getIndivRecords = function (req, res, next) {
res.send({
Result: connection + "This is result"
});
return next();
};
}).catch(function (err) {
res.status(400).send(err);
return;
});
var mysql = require('mysql');
exports.connExport = function () {
return new Promise(function (fulfill, reject) {
var connectionPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
if (connectionPool) {
connectionPool.getConnection(function (err, connection) {
if (err) {
return reject(err);
} else {
return fulfill(connection);
}
});
} else {
var abc = "return error";
return reject(abc);
}
});
}

Categories