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 + "'"
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);
})
});
I have a random generated string that I set as a value for a property in my database table. On a successful update to my record I then send an email containing that same token that was used in the database record. Unfortunately the token parameter in my then statement does not contain the token and instead is replaced with a value of 1. Why is this happening and does it have something to do with how promises functionality works?
This is an example console log and SQL update that appears in my code:
This is the token: 78a4543cdd4cfd9d8c7fbad89aed9f902e07c372
Executing (default): UPDATE `user` SET `reset_password_token`='78a4543cdd4cfd9d8c7fbad89aed9f902e07c372',`reset_password_expires`='2016-04-02 14:46:13',`updatedAt`='2016-04-02 13:46:13' WHERE `email` = 'tester#gmail.com'
Then this token: 1
POST Method:
.post(function(req, res){
async.waterfall([
function(done){
crypto.randomBytes(20, function(err, buf){
var resetToken = buf.toString('hex');
done(err, resetToken);
});
}, (function(token, done){
console.log('This is the token: ' + token);
models.User.update({
resetPasswordToken: token,
resetPasswordExpires: Date.now() + 3600000
}, {
where: { email: req.body.email }
}).then(function(token, user, done){
console.log('Then this token: ' + token);
var transporter = nodemailer.createTransport(sgTransport(options));
var mailOptions = {
from: '"Test Email" <test#mywebsite.com',
to: 'tester#gmail.com',
subject: 'Password Rest Confirmation',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
res.redirect('/');
//res.redirect('/password-reset-confirmation') Make a confirmation page with information or just send a flash message
})
})], function(error){
if(error){
console.log(error);
}
})
});
The token receives the value 1 because the update() operation returns the number of affected records. In this case, there was a single record updated.
Somewhat new to this, but I'm having an issue inserting a variable into my sqlite3 query. I get the error { [Error: SQLITE_ERROR: no such column: shmee] errno: 1, code: 'SQLITE_ERROR' } where shmee in this case is req.body.username
Not sure what I'm doing wrong here? Any guidance?
app.post('/users/login', function (req, res) {
console.log(req.body)
var query = "SELECT username, password FROM users WHERE username = "+req.body.username+";"
db.all(query, function (err, data) {
if (err) {
console.log(err);
} else if (req.body.password === data.password) {
//set cookie with user info
req.session.user = data;
res.redirect('/users/'+data.username);
} else {
console.log(data)
console.log('password not correct');
res.redirect('/cbt');
}
})
});
Do not concatenate data into query strings; this is a serious source of security vulnerabilities!
Use query parameters; wherever you want to pass data into a query, put a ?, and pass it as an additional argument to run:
db.run("SELECT username, password FROM users WHERE username = ?",
username,
function(err, data) {...});
Also hash your passwords.
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.