Javascript MySQL Connection on HTML Page - javascript

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.

Related

Node.js mysql connection only works while executed with command prompt

I am still new to node.js so I apologize in advance if this question is silly.
First I have tried to execute the test.js with command prompt
conn.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'tgs'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
test.js
function testconnect()
{
var conn = require('./conn');
var sql = "INSERT INTO chat_line (line_text) VALUES ('test')";
conn.query(sql, function (err, result) {
if (err) throw err;
});
}
testconnect();
in the command prompt
D:\xampp\htdocs\TGS\>node test.js
and it works, I did get the input in my database. After that I wanted to try to implement this in my system so I have tried to execute this in php
testing.php
<script>
function testalert()
{
alert("alert1");
var conn = require('./conn');
var sql = "INSERT INTO chat_line (line_text) VALUES ('test')";
conn.query(sql, function (err, result) {
if (err) throw err;
});
alert("alert2");
}
</script>
<input type="button" onclick="testalert();">
and it doesn't work. The first alert did pop up after clicking the button but the second alert did not, also there is no input in my database.
Node.js and PHP are different technologies, you cannot directly use one in another if you want to interact with one another you will need some mediator like (API, queue, database etc).
try to understand how nodeJs works, there is a dependency of mysql library at line one, which is a middleware helping with dealing with database
var mysql = require('mysql');
above line can only work in nodeJs environment, if you want to use it in PHP then there will be some other library in PHP to do same (I am not PHP guy so cannot help with ideal one here) and you will not need nodeJS at all with your example.
do let me know if I made it clear.

MySQL not returning data in Node

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?

Impossible to create users (or custom-based roles) in Mongo on server NodeJS

I am trying to create users on my database directly from our Express server, using Mongo 3.4 for the database. Here is the code for the server for now:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://mongo:27017/myDb';
var dbvotes = "collection1";
var dbusers = "collection2";
//Functions for users
app.post('/newUser', function(req, res, db) {
MongoClient.connect(url, function(err, db){
//Ecriture dans la base user
db.collection(dbusers).insertOne( {
"name" : req.body.name,
"surname" : req.body.surname,
"username" : username,
"password" : "pasadmin",
});
//Creation of the user in the DB
db.createUser( { 'user': username, 'pwd': "pasadmin", roles: [] });
db.close();
});
console.log("Inserted a new user in the database.");
res.send("User added. Click precedent to add a new user.");
});
However, whenever the client tries to insert a new user, it is effectively created in the user collections, but not as a user of the database as I get the following error: TypeError: db.createUser is not a function
web_1 | at /app/app.js:47:6.
I have tried to user db.addUser instead, however, this is deprecated since Mongo 2.6 and not working either, and db.adminCommand serves the same error, db.adminCommand is not a function. Before that, I struggled to create custom roles in the database with Node and decided to do it via the Mongo shell as well, but it's not an option when it comes to adding user 1 by 1 in the database.
When I use these functions in the Mongo shell, the commands are working, so I suppose it comes from the way I implemented Mongo within the server (via Docker), or due to some limitations with Javascript. Any idea what could it be?
Thanks in advance to the community!
The proper command would be:
db.addUser( username, password, { roles: [ role ] } );
Where role is some MongoDB role. More info can be found from the source file. It can also be an object in the formation of { role: <string>, db: <string> }, where role is a MongoDB role and db is the string name of the database.
You can also use db.admin().addUser. This would be the logical choice if the user has access to multiple databases or you want a central location of your users.
However, I can't imagine it's a good idea to add system users from your application unless you're developing an actual administrative tool. Normal "users" added to a database would be in your own users collection. A system user is someone who has direct access to your database.

how should I apply sync node.js module with mysql, socket functions?

I'm trying to understand and use sync-npm module, but not sure how to change my functions below to match sync format... (https://www.npmjs.com/package/sync)
Basically I'm trying to use input data (which is formed as a list in client side) I receive from frontend(client) and send it to node.js via socket. I tried to store it in my global variable 'query', but I learned that it doesn't get updated. So when I tried to print 'query' outside of socket function, it doesn't work.
It sounds like I should use sync module, but I'm not quite sure how to implement that in my code...If anyone could give me an idea how to change my functions below, it would be great..thanks!
Receiving input data from frontend and sending it to node.js via socket
var server = app.listen(3001);
var socket = require('socket.io');
var io = socket(server);
var query = []
// Register a callback function to run when we have connection
io.sockets.on('connection',newConnection);
function newConnection(socket){
console.log('new connection: ' + socket.id);
socket.on('search', newSearch);
function newSearch(final){
query.push(final)
console.log(query[0]);
console.log(Array.isArray(query[0])); //returns True
console.log(query[0][0]); // this also works
console.log(query[0][1]);
}
}
console.log('print');
console.log(query);
// this only gets printed in the beginning as an empty array
Ultimately, I'm parsing that list of input data and concat into my sql select phrase. Below is my DB portion code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '~~~',
user : '~~~',
password : '~~~',
database : '~~~'
});
connection.connect();
console.log('mysql connected');
var sql = 'select' + '*' + 'from EBN ';
//ideally data in the 'query' list will concat with this sql string
connection.query(sql,function(err,rows,fields){
if(err){
console.log(err);
}
else{
fs.writeFileSync('search.json', JSON.stringify(rows), 'utf8');
}
});
Firstly, you should wrap the code that does the query execution in a function, something like
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '~~~',
user : '~~~',
password : '~~~',
database : '~~~'
});
connection.connect();
console.log('mysql connected');
function executeQuery(query)
var sql = 'select' + '*' + 'from EBN ';
//do something with query and add it to the sql string
connection.query(sql,function(err,rows,fields){
if(err){
console.log(err);
}
else{
fs.writeFileSync('search.json', JSON.stringify(rows), 'utf8');
}
}
}
This is necessary because you don't want to execute a query right after starting the server, but only after you received the query message via socket. So now you can call executeQuery(final) in your socket message handler.
You should learn how asynchronous programming and callbacks works in nodejs/javascript, and why you should use it as much as possible for server applications (e.g. use fs.writeFile instead of writeFileSync). You can use packages like sync to make life easier for you, but only when you know exactly what you want to do. Just throwing something with the name 'sync' in it at a problem that might be caused by asynchronicity is not going to work.

function to search database for keywords

trying to get functionality to search a mysql database for keywords using javascript, running into problems with how to execute the commands in js and how to insert the keywords from an input box to the mysql query.
<html>
<head>
<title></title>
<script> function mysqlList(){
var keyword = document.getElementById('keyword').value;
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'xxxxxx',
password : 'xxxxxx',
database : 'joblist',
}
);
connection.connect();
var queryString = 'SELECT name, trello FROM graduates WHERE (name LIKE '%keyword%' OR trello LIKE '%keyword%');
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
var console = console.log('name: ', rows[i].name, '|', 'trello: ', rows[i].trello);
}
});
connection.end();
};
window.console = {
log: function(str){
var node = document.createElement("div");
node.appendChild(document.createTextNode(str));
document.getElementById("myLog").appendChild(node);
}
}
</script>
</head>
<body onload="onload();">
<input type="text" name="enter" class="enter" value="" id="keyword"/>
<button onclick="mysqlList()">run query</button>
<p id="myLog"></p>
</body>
</html>
this is non functional at the moment, but even if anyone could point me in the direction of some good tutorials I would appreciate it.
thanks!
You can't do that.
First: require() is specific to NodeJS. It is not available in the browser. Some of the modules which can be loaded with it are available in the browser, but mysql is not.
Second, and related: You can't connect to a MySQL database directly from a web browser. Javascript running in a browser can only make HTTP connections to web servers, and even then only on a limited basis.
You need to implement an API on the server -- possibly using Node, possibly something else -- to perform a search. Then you can use the XMLHttpRequest browser API -- or something based on it, like $.ajax() in jQuery -- to call that API.

Categories