MySQL not returning data in Node - javascript

I have the following JavaScript that I am executing through Node
function afterConnection() {
var query = connection.query("SELECT * FROM playlist;", function (err, res) {
if (err) throw err;
console.log(res);
connection.end();
});
console.log(`The query that ran: ${query.sql}`)
}
Pretty basic. If I execute this code from my Windows 10 machine running MySQL 8 this logs the result set to the console. If I run this same code on macOS 13.5 running the same version of MySQL the code prints an empty array to the console. I know that I am connected to MySQL because if I change the query to something entirely invalid (like trying to SELECT from a table that doesn't exist) I get an error back saying the Table is invalid. So MySQL is consuming the command but isn't sending back a result. If i run the query directly in MySQL it returns the data I would expect. I have double checked my connection strings and there doesn't seem to be any problem there. Additionally if I run the query directly in Workbench data is returned from there as I would expect. Any thoughts?

Related

Issue while mssql Node.js during parametrized query

I'm doing an INSERT on my backend with node.js using mssql, the problem is: when i run the code the INSERT not work and there's no log error:
str_query= "INSERT INTO t1 (id,age,name) VALUES (#ID,#AGE,#NAME) ";
request.input('ID',sql.int,NULL);
request.input('NAME',sql.varchar,NULL);
request.input('AGE',sql.int,NULL);
request.query(str_query, function (err, recordset) {//doing stuff}
So basically seems impossibile to insert a null value in a INT column. Is there any way?

SQL injection in Node Mysql library

I was trying to do some sql injection in node mysql library.
I have an Insert query written in Nodejs using by doing:
pool.query(`Insert into orders(orderType,CustomerID,storeNumber,stageNumber) Values('${orderType}',${customerID},'${storeNumber}','${stageNumber}')`,function(err,rows,fields){
if(err){
console.log(err)
}
var orderID=rows.insertId
}
All of the varaibles comes form a form which I am receiving using req.body
In the stageNumber field in the form instead of the storeNumber I was writing:
'); Delete from orderDetail;
This did not delete anything from my table
From my console.log(err) i get
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 orderDetail;')'
I cannot think of a way to remove the ')' but I know where it is coming from. Is it even possible to do SQL injection in Node MySQL library?
Have you already tried
'); Delete from orderDetail; --
This will ignore any characters post -- and should ideally work in this case.

Stored procedure azure Cosmos DB returns empty collection

I tried to create a stored procedure using the sample sp creation code from Azure docs, but i couldn't fetch the collection details. It always returns null.
Stored Procedure
// SAMPLE STORED PROCEDURE
function sample(prefix) {
var collection = getContext().getCollection();
console.log(JSON.stringify(collection));
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root r',
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var response = getContext().getResponse();
var body = { prefix: prefix, feed: feed[0] };
response.setBody(JSON.stringify(body));
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
The console shows only this.
the results shows no doc found because of not getting collection.I have passed the partition key at time of execution via explorer.
I had a similar issue. I think the Azure portal doesn't execute stored procedures properly when the partition key is not a string.
In my case I had a partitionKey that is a number. When I executed the stored procedure via the portal I always got an empty resultSet, even though I had documents in my database. When I changed the structure a little, and made my partitionKey a string, the stored procedure worked fine.
Did you create the ToDoList Database with the Items Collection? Yo can do this from the Quick start blade in the Azure portal.
And then create an SP to run against that collection. There is no partition key required, so no additional params are required (leave blank).
The Collection is created without any documents. You may choose to add documents via the Query Explorer blade or via the sample ToDoList App that is available via the Quick start blade.
You are debugging in a wrong way.
It is perfectly fine to see "{\"spatial\":{}}" in your console log, even if the collection has items. Why? well because that is a property of that object.
So regarding what you said:
the results shows no doc found because of not getting collection
is false. I have the same console log text, but I have items in my collection.
I have 2 scenarios for why your stored procedure return no items:
I had the same issue trying on azure portal UI(in browser) and for my surprise I had to insert an item without the KEY in order that my stored procedure to see it.
On code you specify the partition as a string ie. new PartitionKey("/UserId") instead of your object ie. new PartitionKey(stock.UserId)

MongoDB db.collection.insertOne crashing after writing to DB

I'm currently using the 'mongodb' package to connect to a local mongo server but the application keeps crashing after creating a user. The data is been written to the local database but when the promise is calling the callback function the MongoDB package throws an error (authorization is not defined). Any ideas as of why this could be happening?
The server crashes inside the /auth/signup route. Essentially I parse the user input to check that the data provided by the user is in the correct format and then I create the structure that I'll write back to the database. I'm currently writing back a class called User with a structure like this:
class User {
strategy = ...
email = ...
displayName = ...
salt = ...
password = ...
}
After checking that no other user with this particular email has been created, I create the new User instance and insert it into mongoDB as shown below:
db.collection('users').insertOne(user, (err, result) => {
if(err){ return res.status(400).send({ error: 'failed to store new user to DB'}); }
//respond to request indicating the user was created
return res.status(200).send({token: authorization.tokenForUser(user)});
});
The application crashed after writing but before the callback. This is the error I'm getting:
.../auth/node_modules/mongodb/lib/utils.js:132
throw err;
^
ReferenceError: authorization is not defined
at db.collection.insertOne (.../auth/routes/authRoutes.js:93:45)
at result (.../auth/node_modules/mongodb/lib/utils.js:410:17)
at executeCallback (.../auth/node_modules/mongodb/lib/utils.js:402:9)
at insertDocuments (.../auth/node_modules/mongodb/lib/operations/collection_ops.js:891:19)
at handleCallback (.../auth/node_modules/mongodb/lib/utils.js:128:55)
at coll.s.topology.insert (.../auth/node_modules/mongodb/lib/operations/collection_ops.js:863:5)
at .../auth/node_modules/mongodb-core/lib/connection/pool.js:397:18
at process._tickCallback (internal/process/next_tick.js:150:11)
I believe the errors has to do with the way I'm using the mongoDB pool I initialize when the application starts running. Any help would be much appreciated.

Javascript MySQL Connection on HTML Page

I'm using node.js's node-mysql driver for MySQL. I wrote this scrap of code
var mysql = require("mysql");
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password : "",
database : "story"
});
function testQuery() {
connection.query("INSERT INTO stories (TITLE, AUTHOR, STORY) VALUES
(\"hello\",\"goodbye\",\"sayonara\")", function(err,rows){
if(err) throw err;
} )
return;
}
So when I run the code in the testQuery() function in the node.js command line and it works as expected inserting hello goodbye and sayonara into the mysql database. But when I place the script into a HTML page and have a button onclick run testQuery() I don't get any result.
You are trying to run Nodejs server code on the client, this will not work. Also this would mean you will become hacked instantly because your password is stored in encrypted, plain text and stored on the clients machine. Double no no. You must start a new node instance and serve this code from the server, not from the browser.

Categories