How to fix "err is not defined" error in Nodejs - mysql

I'm trying to establish a connection to mysql database in Nodejs but it won't compile as "err is undefined". I'm fairly new to Node.js, but I thought this was the appropriate way to handle errors, even with the mysql package, which is the only difference from my other projects where I did not encounter this issue.
throw err; // Rethrow non-MySQL errors
^
ReferenceError: err is not defined
const express = require('express');
const mysql = require('mysql');
//Create connection
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database: 'ca1903'
});
//Connect
db.connect(() => {
if(err){
console.log(err);
}
console.log('MySql Connected');
});
const app = express();
//create DB
app.get('/createdb', () => {
let sql = 'CREATE DATABASE ca1903';
db.query(sql, (err, result) => {
if(err){
console.log(err);
}
console.log(result);
res.send('database created....');
});
});

You were missing err parameter in the db.connect call. It should be in the below way.
// Connect
db.connect((err) => {
if(err){
console.log(err);
}
console.log('MySql Connected');
});

Related

Cannot enqueue Handshake after already enqueuing a Handshake

const app = require('./app');
var mysql = require('mysql');
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);
});
I learning nodejs 3 day but i don't know how can i fix it i try to fix it but not work.
Someone Help me please
I don't know what i wrong. I want to insert data into mysql with pug
be like login with html and use php to select data in phpmyadmin
register in pug and data send to nodejs and node post data to mysql
I'm sorry my English and gramma so bad :(
const express = require('express');
var mysql = require('mysql');
const router = express.Router();
const app = require('../app.js');
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "1234",
database:"project_test"
});
conn.connect(function(err) {
if (err) throw err;
console.log("Index Connection!");
});
conn.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customer (name, address) VALUES ('Company Inc', 'Highway 37')";
conn.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
module.exports = router;

Node + Express application returns 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR'?

I'm trying to build an application with Node and Express, it worked well yesterday until today I got this error:
{
code: "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR",
fatal: false
}
Google says I should use createPool rather than createConnection, but I'm not sure how to do it in my case. Here is my code:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
const SELECT_ALL_USERS_QUERY = 'SELECT * FROM `mySchema`.`myTable`;';
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'abcdefg',
database: 'mySchema'
});
connection.connect(err => {
if (err) {
return err
}
});
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /mySchema to see contents')
});
app.get('/myTable', (req, res) => {
connection.query(SELECT_ALL_USERS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
}
})
});
app.listen(4000, () => {
console.log('MySchema SQL server listening on PORT 4000');
});
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host: 'localhost',
user: 'root',
password: 'abcdefg',
database: 'mySchema'
});
// for an example.....
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
app.get('/myTable', (req, res) => {
// Use the connection
connection.query('SELECT something FROM sometable', function (error, results, fields) {
// When done with the connection, release it.
connection.release();
// Handle error after the release.
if (error) throw error;
// Don't use the connection here, it has been returned to the pool.
});
});
});
If you would like to close the connection and remove it from the pool, use connection.destroy() instead. The pool will create a new connection the next time one is needed.
Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.
When a previous connection is retrieved from the pool, a ping packet is sent to the server to check if the connection is still good.
you can follow this link: https://github.com/mysqljs/mysql#pooling-connections
To help other people, thought I'd post the complete solution which worked for me:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /mySchema to see contents')
});
const SELECT_ALL_USERS_QUERY = 'SELECT * FROM `mySchema`.`myTable`;';
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'abcdefg',
database: 'mySchema',
debug: false
});
pool.getConnection((err, connection) => {
if (err) throw err;
app.get('/myTable', (req, res) => {
connection.query(SELECT_ALL_USERS_QUERY, (err, results) => {
if (err) {
return res.send(err)
}
else {
return res.json({
data: results
})
};
});
console.log(connection);
});
});
app.listen(4000, () => {
console.log('MySchema SQL server listening on PORT 4000');
});

NodejS express ReferenceError: connection is not defined

I am creating a simple server application using the following code
const express = require('express');
const mysql = require('mysql');
const PORT = process.env.PORT || 3000;
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'mydata',
});
connection.connect(function (err) {
err ? console.log(err) : console.log(connection);
});
require('./routes/html-routes')(app);
app.listen(PORT, () => {
console.log('app running on port %s', PORT);
});
module.exports = app;
in file server.js
and then a route in file html-routes.js
const mysql = require('mysql');
module.exports = function (app) {
app.get('/', function (req, res) {
connection.query('select * from mydata;', function (err, data) {
err ? res.send(err) : res.json({ mydata: data });
});
});
};
to get data from database
I get the error
ReferenceError: connection is not defined
at /Users/arjunbhandari/Desktop/GL-IT/backend/routes/html-routes.js:5:5
I have struggled for the past 6 hours and cannot understand the problem.
Thanks
As the error states, there is no connection defined (or inherited) within ./routes/html-routes.js.
You still can pass the connection property as a second argument to your exported function:
const mysql = require('mysql');
module.exports = function (app, connection) {
app.get('/', function (req, res) {
connection.query('select * from mydata;', function (err, data) {
err ? res.send(err) : res.json({ mydata: data });
});
});
};
then update the route mounting call within your main server file:
require('./routes/html-routes')(app, connection);
You should review your route implementation logic as this should not be the best design approach to use data-store connections.

Database creation failure, result Undefined

I am trying to create a simple nodejs code using express and mysql.
const express = require('express');
const mysql = require('mysql');
const db = mysql.createConnection({
host : 'localhost',
user : 'admin',
password : ''
});
db.connect((err) => {
if(err){
console.log('Error while connecting');
}
console.log('Connected');
});
const app = express();
app.get('/createdb',(req, res) => {
let sql = 'CREATE DATABASE nodemysql';
db.query(sql,(err,result) => {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});
app .listen('4200',() => {
console.log('Server started on port 4200');
});
The response is sent to the browser that says
database created..
but the result it throws is undefined. Also the console that says
Error while creating database is printed
Error I am getting is
[nodemon] restarting due to changes...
[nodemon] restarting due to
changes... [nodemon] starting node index.js
Server started on port 4200
Connected error while creating database
result: undefined
I am not sure on what I am missing out. Please help.
Below code should work fine, try to execute the below code in a .js file. If it works, then we would be sure that nothing wrong in the conf part.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
I am not an expert, but added the keyword 'function', like below:
app.get('/createdb',(req, res) => {
let sql = 'CREATE DATABASE nodemysql11';
db.query(sql, function(err,result) => {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});
Try this, it will work
app.get('/createdb',(req, res) => {
db.query('CREATE DATABASE nodemysql11', function(err,result) {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});
Try the below line and then run the .js file.
I assume u have done npm install mysql
mv ./node_modules/node-mysql/node_modules/* ./node_modules/

How to provide a mysql database connection in single file in nodejs

I need to provide the mysql connection for modules. I have a code like this.
var express = require('express'),
app = express(),
server = require('http').createServer(app);
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'chat'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
});
app.get('/save', function(req,res){
var post = {from:'me', to:'you', msg:'hi'};
var query = connection.query('INSERT INTO messages SET ?', post, function(err, result) {
if (err) throw err;
});
});
server.listen(3000);
But how we provide one time mysql connection for all the modules.
You could create a db wrapper then require it. node's require returns the same instance of a module every time, so you can perform your connection and return a handler. From the Node.js docs:
every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
You could create db.js:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'chat'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
Then in your app.js, you would simply require it.
var express = require('express');
var app = express();
var db = require('./db');
app.get('/save',function(req,res){
var post = {from:'me', to:'you', msg:'hi'};
db.query('INSERT INTO messages SET ?', post, function(err, result) {
if (err) throw err;
});
});
server.listen(3000);
This approach allows you to abstract any connection details, wrap anything else you want to expose and require db throughout your application while maintaining one connection to your db thanks to how node require works :)
I took a similar approach as Sean3z but instead I have the connection closed everytime i make a query.
His way works if it's only executed on the entry point of your app, but let's say you have controllers that you want to do a var db = require('./db'). You can't because otherwise everytime you access that controller you will be creating a new connection.
To avoid that, i think it's safer, in my opinion, to open and close the connection everytime.
here is a snippet of my code.
mysq_query.js
// Dependencies
var mysql = require('mysql'),
config = require("../config");
/*
* #sqlConnection
* Creates the connection, makes the query and close it to avoid concurrency conflicts.
*/
var sqlConnection = function sqlConnection(sql, values, next) {
// It means that the values hasnt been passed
if (arguments.length === 2) {
next = values;
values = null;
}
var connection = mysql.createConnection(config.db);
connection.connect(function(err) {
if (err !== null) {
console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
}
});
connection.query(sql, values, function(err) {
connection.end(); // close the connection
if (err) {
throw err;
}
// Execute the callback
next.apply(this, arguments);
});
}
module.exports = sqlConnection;
Than you can use it anywhere just doing like
var mysql_query = require('path/to/your/mysql_query');
mysql_query('SELECT * from your_table where ?', {id: '1'}, function(err, rows) {
console.log(rows);
});
UPDATED:
config.json looks like
{
"db": {
"user" : "USERNAME",
"password" : "PASSWORD",
"database" : "DATABASE_NAME",
"socketPath": "/tmp/mysql.sock"
}
}
Hope this helps.
I think that you should use a connection pool instead of share a single connection. A connection pool would provide a much better performance, as you can check here.
As stated in the library documentation, it occurs because the MySQL protocol is sequential (this means that you need multiple connections to execute queries in parallel).
Connection Pool Docs
From the node.js documentation, "To have a module execute code multiple times, export a function, and call that function", you could use node.js module.export and have a single file to manage the db connections.You can find more at Node.js documentation. Let's say db.js file be like:
const mysql = require('mysql');
var connection;
module.exports = {
dbConnection: function () {
connection = mysql.createConnection({
host: "127.0.0.1",
user: "Your_user",
password: "Your_password",
database: 'Your_bd'
});
connection.connect();
return connection;
}
};
Then, the file where you are going to use the connection could be like useDb.js:
const dbConnection = require('./db');
var connection;
function callDb() {
try {
connection = dbConnectionManager.dbConnection();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (!error) {
let response = "The solution is: " + results[0].solution;
console.log(response);
} else {
console.log(error);
}
});
connection.end();
} catch (err) {
console.log(err);
}
}
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'yourip',
port : 'yourport',
user : 'dbusername',
password : 'dbpwd',
database : 'database schema name',
dateStrings: true,
multipleStatements: true
});
// TODO - if any pool issues need to try this link for connection management
// https://stackoverflow.com/questions/18496540/node-js-mysql-connection-pooling
module.exports = function(qry, qrytype, msg, callback) {
if(qrytype != 'S') {
console.log(qry);
}
pool.getConnection(function(err, connection) {
if(err) {
if(connection)
connection.release();
throw err;
}
// Use the connection
connection.query(qry, function (err, results, fields) {
connection.release();
if(err) {
callback('E#connection.query-Error occurred.#'+ err.sqlMessage);
return;
}
if(qrytype==='S') {
//for Select statement
// setTimeout(function() {
callback(results);
// }, 500);
} else if(qrytype==='N'){
let resarr = results[results.length-1];
let newid= '';
if(resarr.length)
newid = resarr[0]['#eid'];
callback(msg + newid);
} else if(qrytype==='U'){
//let ret = 'I#' + entity + ' updated#Updated rows count: ' + results[1].changedRows;
callback(msg);
} else if(qrytype==='D'){
//let resarr = results[1].affectedRows;
callback(msg);
}
});
connection.on('error', function (err) {
connection.release();
callback('E#connection.on-Error occurred.#'+ err.sqlMessage);
return;
});
});
}
try this
var express = require('express');
var mysql = require('mysql');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
console.log(app);
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "admin123",
database: "sitepoint"
});
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
module.exports = app;
you can create a global variable and then access that variable in other files.
here is my code, I have created a separate file for MySQL database connection called db.js
const mysql = require('mysql');
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "xxxxx",
database: "test"
});
conn.connect((err) => {
if (err) throw err;
console.log('Connected to the MySql DB');
});
module.exports = conn;
Then in the app.js file
const express = require('express');
const router = express.Router();
// MySql Db connection and set in globally
global.db = require('../config/db');
Now you can use it in any other file
const express = require('express');
const router = express.Router();
router.post('/signin', (req, res) => {
try {
var param = req.body;
var sql = `select * from user`;
// db is global variable
db.query(sql, (err, data) => {
if (err) throw new SyntaxError(err);
res.status(200).json({ 'auth': true, 'data': data });
});
} catch (err) {
res.status(400).json({ 'auth': false, 'data': err.message });
}
});