MYSQL Node Issue - javascript

Running the below code throws a MYSQL err, I've checked the syntax and it seems correct but not sure why the error is being thrown.
app.post('/:roomname/create',function(request, response){
let roomID = ""+request.params.roomname+"";
console.log(roomID);
let insertRoom = "INSERT INTO chatrooms (roomname) VALUES (?)";
conn.query(insertRoom,[roomID], function(error, result) {
if (err) throw err;
console.log("1 record inserted");
});
Error:
node_modules/mysql/lib/protocol/Parser.js:80
throw err; // Rethrow non-MySQL errors
^
ReferenceError: err is not defined

Your handling error name and callback error name is not same!
you must define same error name in both callback and handling block.
Please check use this snipet. After use this snipet if any error happening, please let me know in comment.
app.post('/:roomname/create',function(request, response){
let roomID = ""+request.params.roomname+"";
console.log(roomID);
let insertRoom = "INSERT INTO chatrooms (roomname) VALUES (?)";
conn.query(insertRoom,[roomID], function(err, result) {
if (err) throw err;
console.log("1 record inserted");
});

conn.query(insertRoom,[roomID], function(error, result) {
if (err) throw err;
In the callback function you are writing "error" but in the if you are checking "err". In the callback change it to
conn.query(insertRoom,[roomID], function(err, result) {

Related

How to resolve error require() is not defined when calling a function from JavaScript to Node.js

I am trying to create a website and found out that Javascript does not have any way to contact a database. I did some research and found out about node.js. I created a node.js file and a small portion of my code is:
var mysql;
var con;
function initialise() {
mysql = require('mysql');
con = mysql.createConnection({
host: "name of the server the database is on",
user: "name of user that has can add and delete stuff to the database",
password: "password for the user",
database: "name of the database"
});
con.connect(function(err) {
if (err) throw err;
});
}
function getCoach(sql, con) {
return new Promise((resolve, reject) => {
con.query(sql, function (err, rows, fields) {
if (err) {
reject = (err);
throw err;
}
resolve(rows);
});
});
}
async function info() {
con.connect(function(err) {
if (err) throw err;
});
const results2 = await getCoach("SELECT username, password FROM coach", con);
return results2;
con.end();
}
I need the require('mysql') inorder to connect with the database. I tested it out and I can get a connection with the database on this file, but when I called a function in the node.js file through Javascript I got an error saying that require() is not defined. I did some research and found many things like Browserify to try and fix this issue, but nothing is working. How do I remove the error so that I can connect to the database that I created through JavaScript. What am I missing and is there a better way of doing this?
Try including your require statement outside the function like this:
const mysql = require("mysql")

Building a massive query based on single query [duplicate]

I'm using nodejs 10.26 + express 3.5 + node-mysql 2.1.1 +
MySQL-Server Version: 5.6.16.
I got 4 DELETE's and want only 1 Database Request, so i connected the DELETE commands with a ";"... but it fails always.
var sql_string = "DELETE FROM user_tables WHERE name = 'Testbase';";
sql_string += "DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase';";
connection.query(sql_string, function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
It throws this error:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';DELETE FR' at line 1
But if i paste this SQL in PhpMyAdmin it is always successful...
If i write it in single query's its succeed, too.
connection.query("DELETE FROM user_tables WHERE name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
});
});
});
Thanks for help!
I guess you are using node-mysql. (but should also work for node-mysql2)
The docs says:
Support for multiple statements is disabled for security reasons (it
allows for SQL injection attacks if values are not properly escaped).
Multiple statement queries
To use this feature you have to enable it for your connection:
var connection = mysql.createConnection({multipleStatements: true});
Once enabled, you can execute queries with multiple statements by separating each statement with a semi-colon ;. Result will be an array for each statement.
Example
connection.query('SELECT ?; SELECT ?', [1, 2], function(err, results) {
if (err) throw err;
// `results` is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
So if you have enabled the multipleStatements, your first code should work.
Using "multiplestatements: true" like shown below worked for me
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: '',
multipleStatements: true
});
connection.connect();
var sql = "CREATE TABLE test(id INT DEFAULT 1, name VARCHAR(50));ALTER TABLE test ADD age VARCHAR(10);";
connection.query(sql, function(error, results, fields) {
if (error) {
throw error;
}
});
To Fetch Data from DB(SQL), the following function would work accurately
router.get('/', function messageFunction(req, res){
//res.send('Hi Dear Rasikh, Welcome to Test Page.') //=> One Way
dbConn.query('SELECT COUNT(name) as counted, name, last_name, phone, email from students',
function (err, rows, fields) { // another Way
if (err) throw err
dbConn.query('SELECT name, author from books',
function (err, rowsBook, fields) { // another Way
if (err) throw err
// console.log('The counted is: ', rows[0].counted); //=> Display in console
// res.send('Hi Dear Rasikh, Welcome to Test Page.'+ rows[0].counted) //=> Display in blank page
res.render('main/index',{data:rows, myData:rowsBook});
})
});
});

Error from node-js mysql connection doesn't get saved to array

Im trying to keep a record from all my errors in a WebService I'm making in node-js;
I've written the following code to keep track of a mysql query possible error:
var err_db = [];
try{
if(error.length == 0){
...
var con = mysql.createConnection({
host: "my_host",
user: "my_user",
password: "my_pass",
database: "my_db"
});
con.connect(function(err) {
if (err) err_db[err_db.length] = err.message;
con.query("IM TRYING HARD TO GET AN SQL ERROR", function (err) {
if (err) err_db[err_db.length] = err.message;
console.log(err_db); //FIRST LOG SHOWS CORRECT
});
console.log(err_db); // THE ERROR DISAPEARS FROM ARRAY
});
}
}
catch(err){
if(err) err_db[err_db.length] = err.message;
}
The problem is the error only keeps stored in array inside the con.query function, after that it disappear, and I want to keep it in a array because later on I intend in sending this possible errors as a JSON to through the WebService response. Thanks in advance.
This is a normal asynchronous nature of node.js. Since the query is executed in a slight greater time so next line is executed first.
try{
if(error.length == 0){
...
var con = mysql.createConnection({
host: "my_host",
user: "my_user",
password: "my_pass",
database: "my_db"
});
con.connect(function(err) {
if (err) err_db[err_db.length] = err.message;
con.query("IM TRYING HARD TO GET AN SQL ERROR", function (err) {
if (err) err_db[err_db.length] = err.message;
console.log(err_db); //FIRST LOG SHOWS CORRECT
// throw the error from here
});
console.log(err_db); // THIS EXECUTED EARLIER THAN THE PREVIOUS
});
}
}
catch(err){
if(err) err_db[err_db.length] = err.message;
}
Asynchronous code cannot catch exceptions using try-catch.
You can try the following code.
var EventEmitter = require('events');
var emitter = new EventEmitter();
var err_db = [];
var con = mysql.createConnection({
host: "my_host",
user: "my_user",
password: "my_pass",
database: "my_db"
});
if (error.length == 0) {
con.connect(function (err) {
if (err) {
emitter.emit('err_db', err);
return;
}
con.query("IM TRYING HARD TO GET AN SQL ERROR", function (err) {
// if (err) err_db[err_db.length] = err.message;
// console.log(err_db); //FIRST LOG SHOWS CORRECT
if (err) {
emitter.emit('err_db', err);
return;
}
});
console.log(err_db); // THE ERROR DISAPEARS FROM ARRAY
});
}
emitter.on('err_db', (err) => {
// handle db err...
err_db[err_db.length] = err.message
});

bcrypt 'cb not a function' error

(Assume the hashing has been done) I am trying to do an authenticate user function, by comparing an entered password and its hash in my MongoDB collection. This is my the method in my model.js (copied from the bcrypt guide):
PetOwnerSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
And my controller.js:
exports.check = function (req, res) {
var email = req.body['email'];
var password = req.body['password'];
PetOwner.findOne({ "email" : email}, 'email', function(err, task) {
if (err)
res.send(err);
if ( task === null ){
res.json(0); // no matching result
console.log("Email is not yet registered");
} else {
task.comparePassword(password, task.password, function(err, isMatch) { //compare password and the already-hashed password in MongoDB
if (err) throw err;
if(isMatch){
res.json(1);
console.log("Found matching password to email");
}
else{
res.json(0);
console.log("Wrong password");
}
});
}
})
};
And when I fetch the check method, the node console prompts the error that the cb in my model.js is not a function. I have tried several workaround but none has worked so far. Is there any way to debug this?
PetOwnerSchema.methods.comparePassword = function(candidatePassword, cb)
Your function takes a single parameter so you cannot refer to a context of "this" outside the function, like you do by using "this.password".
If you add the password to compare with as a second parameter like so:
PetOwnerSchema.methods.comparePassword = function(candidatePassword, password2, cb)
You can then just compare the two inside the function as you are trying to do.
Hope it helps

MEAN CRUD error crash cant set headers

So my CRUD app at this time, does two things, keeps sending an infinite empty list. But not just that, when I try to delete something I get this error... Jump below for the api code. Also if you see anything that might contribute to an infinite list lemme know.
C:\Users\\Desktop\Todo List\node_modules\mongoose\lib\utils.js:419
throw err;
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
at ServerResponse.res.setHeader (C:\Users\\Desktop\Todo List\node_modul
es\express\node_modules\connect\lib\patch.js:63:22)
at ServerResponse.res.set.res.header (C:\Users\\Desktop\Todo List\node_
modules\express\lib\response.js:526:10)
at ServerResponse.res.json (C:\Users\\Desktop\Todo List\node_modules\ex
press\lib\response.js:193:36)
at Promise.<anonymous> (C:\Users\\Desktop\Todo List\routes\api.js:45:21
)
at Promise.<anonymous> (C:\Users\\Desktop\Todo List\node_modules\mongoo
se\node_modules\mpromise\lib\promise.js:162:8)
at Promise.EventEmitter.emit (events.js:95:17)
at Promise.emit (C:\Users\\Desktop\Todo List\node_modules\mongoose\node
_modules\mpromise\lib\promise.js:79:38)
at Promise.fulfill (C:\Users\\Desktop\Todo List\node_modules\mongoose\n
ode_modules\mpromise\lib\promise.js:92:20)
at C:\Users\\Desktop\Todo List\node_modules\mongoose\lib\query.js:1736:
26
routes api code
var Todo = require('../app/models/todos').Todo;
exports.read = function(req, res) {
// use mongoose to get all todos in the database
Todo.find(function(err, todos) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (!err)
res.send(err)
res.json(todos); // return all todos in JSON format
});
};
// create todo and send back all todos after creation
exports.create = function(req, res) {
// create a todo, information comes from AJAX request from Angular
Todo.create({text : req.body.text}, function(err, todos) {
if (err)
res.send(todos);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
};
// delete a todo
exports.delete = function(req, res) {
Todo.remove({_id : req.params._id
}, function(err, todos) {
if (err)
res.send(todos);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
};
//Update a todo
exports.update = function(req, res) {
Todo.findById(req.params._id, function(err, todos){
todos.text = req.body.text;
console.log(todos);
todos.save(function() {
if (!err) {
res.send(todos);
} else if (err) {
res.send(err);
}
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
};
I usually see this error when I'm using res multiple times in my Express route by mistake. Be sure that in route handler (function) you are only using res once.
For example
app.get('/foo', doFoo);
function doFoo(req, res) {
res.send('foo');
res.send('bar');
}
won't work since you're trying to use res twice which internally calls res.end() if I'm not mistaken.
Edit: As it turns out, I think I see the problem in your code.
// create a todo, information comes from AJAX request from Angular
Todo.create({text : req.body.text}, function(err, todos) {
if (err)
res.send(todos);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
Here, you're using res.send(todos) in the event that you receive an error from your first call to Todo.create. Assuming you do receive an error here, your code will still attempt Todo.find. Once that happens, it will then try res.json(todos) thereby firing two responses and resulting in the error that you see about not being able to set response headers after they're already sent. I think you can fix your code by using actual else statements to ensure you don't send two responses.
Todo.create({text:req.body.text}, function(err, todos){
if (err) {...}
else {
.. your else code here
}
});

Categories