New to node.js and just cant figure out how to do the following:
I have this on my db module:
var mysql = require('mysql');
var MY_DATABASE='nodejs_mysql';
var client = mysql.createClient({
user: 'root',
password: 'root',
});
and im building this table:
client.query(
'CREATE TEMPORARY TABLE '+USER+
'(username VARCHAR(255), '+
'password VARCHAR(255), '+
'name VARCHAR(255), '+
'picture VARCHAR(255), '+
'PRIMARY KEY(username))'
);
and later on, i want to perform this:
client.query('select username, password from ' + USER + 'where username=?',[req.body.username] , 'AND password=?', [req.body.password]
function (err, results, fields) {
if (err) {
throw err;
}
//some actions performed here
});
all of those are in the same dataBase.js file.
how can i send username and password from another file named: server.js
as parameters to the query written above and get a certain value back?
is there any way to do that?
Ok, I think I get it now. You create temporary table in dataBase.js and want to perform query in this table in request handler in server.js. If that's it, you should consider following aproach:
// dataBase.js
var mysql = require('mysql');
var MY_DATABASE='nodejs_mysql';
// connect to database
var client = mysql.createClient({
user: 'root',
password: 'root',
});
// create temporary table
client.query(
'CREATE TEMPORARY TABLE '+USER+
'(username VARCHAR(255), '+
'password VARCHAR(255), '+
'name VARCHAR(255), '+
'picture VARCHAR(255), '+
'PRIMARY KEY(username))'
);
// that's what I think you need. And yes, it looks like "a good to rap" for me.
module.exports.getInfoFromTemporaryTable : function( username, password, callback) {
client.query(
'select username, password from ' + USER + 'where username=?',
[req.body.username] , 'AND password=?', [req.body.password],
callback
);
}
The only thing I can't figure out is where you get USER variable from. Pay attention to this moment. Maybe pass it to getInfoFromTemporaryTable() function.
// server.js
var db = require('./lib/dataBase');
app.get(someRoute, function(req, res) {
db.getInfoFromTemporaryTable( req.body.username, req.body.password,
function(err, results, fields) {
if (err) {
// handle errors or something
return;
}
// do what you need to do, using results you got from temp table
});
});
I'm not familiar with MySQL module you using, so above code is more like a general idea of what you need to implement. Hope it will help.
how can i send username and password from another file named: server.js
as parameters to the query written above and get a certain value back?
Use the exports object. See here for more information on NodeJS's module system.
// server.js
exports.username = function {
return "foo";
};
exports.password = function {
return "bar";
};
// database.js
require('./server.js');
var client = mysql.createClient({
user: server.username, // exports.username in server.js
password: server.password, // exports.password in server.js
});
Why are you splitting your query up?
// server.js
exports.username = "Your username.";
exports.password = "Your password.";
// dataBase.js
// ... mysql connection setup ...
var server = require("./server");
client.query('SELECT username, password FROM `' + USER + '` WHERE username=? AND password=?',
[server.username, server.password],
function (err, results, fields) {
if (err) {
throw err;
}
// ... some actions performed here ...
}
);
I'm not exactly sure what you were asking, but I think this should at least get you closer to your answer.
Related
I encountered a weird bug when doing a quick coding assignment.
Here is my code.
Lets call this 'A'
//Grab all the animals from the database
WebApp.get('/all',(req,res) =>
{
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234', //Enter your password here
// I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
database: 'animals'
});
const query = "SELECT * FROM animals";
connection.query(query, (err, rows, fields) =>
{
if (err)
{
console.error('error : ' + err.stack);
res.sendStatus(500);
return;
}
console.log("Fetched animals successfully");
//console.log(rows); // Use this for error checking to see if a authent problem occurs.
res.json(rows);
});
});
and this 'B'
//Grab a selected animal from the database given a valid Id.
WebApp.get('/:id',(req,res) =>
{
console.log("Fetching user with id: " + req.params.id);
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234', //Enter your password here
// I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
database: 'animals'
});
const animalId = req.params.id;
const query = "SELECT * FROM animals WHERE id = ?";
connection.query(query, [animalId], (err, rows, fields) =>
{
if (err)
{
console.error('error : ' + err.stack);
res.sendStatus(500);
return;
}
console.log("Fetched animals successfully");
//console.log(rows); // Use this for error checking to see if a authent problem occurs.
res.json(rows);
});
});
For some reason, if I put A before B it works, and I get successful results from my queries. However, if I put B before A, B will return successfully, but A will return '[]'. Anyone know why?
Thanks for any help!
Have you tried terminating the connection after each request, or considered using a connection pool? I am not familiar with nodeJS integration with MySQL, but in SQLServer, it is best to use ConnectionPool, when asynchronously making database requests.
I know how to query a SQLite Database with Node.js to bring back a specific key with the corresponding field information but I am unable to find the right syntax to do it in Mysql.
I want to put a specific station name in the url such as and result all its information from the database. example. http://localhost:5000/station/
The database result would be:
["station":"winton", "location":"123 Byers Lane", "property size":"3000"]
<sqlite> needs to be put in <mysql>
app.get('station/:stationid', req, res) => {
const stationToLookup = req.params.stationid;
db.all (
'SELECT * FROM stores WHERE station = $station',
{
$station = stationToLookup
},
(err, rows) => {
console.log(rows);
if (rows.length > 0){
res.send (rows[0]);
}else{
res.send({});
}
});
});
You should install mysql driver first via npm. npm install mysql
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
app.get('station/:stationid', req, res) => {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM stores WHERE station ='" + req.params.stationid + "'", function (err, result) {
if (err) throw err;
console.log(result);
});
});
}
NOTE how the double quotes and single quotes have been used in the code above. The query is inside double quotes and then the value of a field which we are going to find is between single qoutes embedded inside double qoutes just after the = sign.
Here seems to be a solutioin.....#James #SonuBamniya
//(2)getting all stations names
app.get('/stationNames/:stationid',(req,res)=>{
const nameToLookup = req.params.stationid;
//console.log(nameToLookup);
db.query('SELECT * FROM stores WHERE station = ?', [nameToLookup],(err, rows, fields)=>{
if(!err)
res.send(rows);
else
console.log(err);
})
});
Hello I'm just new to Node.js and currently working on session login.
Why can't I set session inside my query function?
Why do I need req.session.save() to save it, but after redirecting to some page session its still not totally set and the page needs to refresh to show session.
Here is my function in setting session
client.query(
"Select id FROM users Where username = '" + req.body.username + "' AND password = '" + req.body.password + "'",
function(err, result) {
if (err) {
return console.error('error running query', err);
} else {
done();
req.session.user_id = result.rows;
req.session.save();
res.redirect('/wall');
}
});
You might want to simplify your example and clarify what libraries you are using. I am assuming you are using express and express-session. I set up a simple example where when you go to to /login?username=yourname page it redirects you to a different page where it shows your name.
var app = require('express')();
var http = require('http').Server(app);
var session = require('express-session');
var mysql = require('mysql')
app.use(session({secret: 'super secret'}));
var client = mysql.createConnection({
host: "My",
user: "private",
password: "configuration",
database: "my_db"
});
app.get('/login', function(req, res, next) {
var sessionData = req.session;
client.query('SELECT * from users where username = ?', [req.query.username], function(err, rows) {
if(err) throw err;
if (rows.length) {
var user = rows[0]
req.session.username = user.username;
req.session.user_id = user.id
res.redirect('/signed_in');
} else {
res.send("user not found")
}
})
})
app.get('/signed_in', function(req, res){
res.send(req.session.user_id + "," + req.session.username);
});
http.listen(3000);
Quentin is right you should look out for sql injections. in the case of node you typically do something like this, depending on what sql library you are using.
client.query(
"Select id FROM users Where username = ? AND password = ?", [req.body.username, req.body.password],
function(err, result) {
// Your code
}
As for why you have to refresh the page after you reload it my guess is something related to done function since i don't know what it is doing in your code. I have no idea why you need to call save, it is not necessary in my example.
I have a stored procedure getUsers in MYSQL that takes in an int and returns a table of users with user data. The stored procedure returns 1 row when I run it in phpmyadmin with a 'name' field, however when I call it from Node.js the row fields return "undefined". I feel like I must be missing something because every other table operation I do with Node.js the same way works, but when I try to call this store procedure it doesn't. Here's my code:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var bcrypt = require('bcrypt');
//constants
const tableName = 'user';
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'users',
charset : 'utf8mb4'
});
//function to insert to or retrieve data from the database
router.post('/', function(req, res, next) {
let userID = req.body.userID;
connection.query(
"CALL `getUsers`(?)",
[userID],
function(err, row, field) {
if (err) {
res.send({ 'success': false, 'message': 'Could not connect. ' + err});
}
if ( row.length > 0 ) {
console.log('name: ' + row[0].name);
res.send({ 'success': true, 'users': row });
} else {
res.send({ 'success': false, 'message': 'No users found.' });
}
});
}
});
the console log returns 'name: undefined', but when I run the procedure in phpmyadmin it returns the row with the correct 'name' field in it.
Syntax should be:
connection.query(`CALL getUsers(?)`, [userID], (err, row, field) => {})
Note the backticks vs. the way you have the double quotes.
Just wanted to let y'all know I fixed the problem by changing row[0].name to row[0][0].name
Turns out stored procedures are unlike regular queries in that they return an array of arrays instead of just one array.
This is my first time working with node and postgre. I am trying to get the email, first name, and last name from my postgre database by passing in a user's email address in a SQL statement:
function getSingleUser(req, response, next){
var UserId = req.params.email.substring(1);
console.log(UserId);
pool.connect(function(err, client, done){
if(err){
return console.error('Error fetching client from pool', err);
}
client.query('SELECT users.email, users.firstname, users.lastname, users.id FROM people.users WHERE users.lastname = Williams', function(err, results){
if(err){
return console.log('error running query', err);
}
// Just returns the raw json data
response.json(results.rows);
client.release();
done();
});
});
};
Whenever I run this though I get the error: error running query { error: column "williams" does not exist. So what can I use to check for a value and not a column? Thank you
Ok I fixed it by adding single quotes around my parameter and double quotes around everything else.
client.query("SELECT users.email, users.firstname, users.lastname, users.id FROM people.users WHERE users.lastname = '" + UserId + "'"