I'm having trouble inserting data into a MySQL database. Select queries work fine, so I'm assuming that it's something stupid that I've missed, either in the Express code, or, in my HTML. The page I'm running the query from is located at localhost:8080/add, and I'm trying to INSERT INTO. Here's my code:
Javascript
app.get('/add', function(req, res) {
res.sendFile(path.join(__dirname + '/Views/add.htm'));
});
app.post('/add', function(req, res) {
var fName = req.body.fName;
var email = req.body.email;
var id = req.body.id;
var post = {id: id, user: fName, email: email};
console.log(post);//This holds the correct data
connection.query('INSERT INTO user VALUES ?', post, function(err, result) {
if (!err) {
console.log('Successfully added information.');
} else {
console.log('Was not able to add information to database.');
}
});
});
My HTML is simply a submit button and 3 input fields, within in a POST method form. Again, I can connect to the database and read from it with a select query, I just cannot insert into it.
Look at the documentation here https://github.com/mysqljs/mysql#escaping-query-values.
connection.query('INSERT INTO posts SET ?', post, function(err, result) {
if (!err) {
console.log('Successfully added information.');
} else {
console.log(result);
console.log('Was not able to add information to database.');
}
});
Valid mysql statement is SET instead of Values.
Related
I am currently working on a login system with Nodejs, Express & MongoDB. Everything works except the values in the database are coming up as undefined. At the two console.log statements where "database ___" is stated, the result is undefined. Not too sure why, from some testing it seems that the user inputted values work fine so I don't know why it's returning undefined.
app.post("/login", (req, res) => {
//Get user fields
const userEmail = req.body.loginEmail;
const userPass = req.body.loginPassword;
//Is user in database?
User.find({ email: userEmail }, (err, user) => {
console.log("database email: " + user.email)
if (!err) {
//Compare password to database password
bcrypt.compare(userPass, user.password, (err, result) => {
console.log("database password: " + user.password);
//If user pass in database, check if verified & redirect to success
if (userPass === user.password) {
if (user.isVerified) {
res.redirect("/success");
} else {
res.send(
"You are not verified. Please check your email to access your account."
);
}
} else {
res.send("Incorrect password");
}
});
} else {
res.send(err);
}
});
});
Mongoose will return an array as the second argument to the callback function when you use find(). If you use findOne() a single document will be returned instead.
I am new with node.js, mongoDB and jade.
To redirect to userlist page I have following route in /routes/index.js
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
This route redirects me to userlist page. There I display a list of all users. Here I have a link on each record to view details:
following is my userlist.jade
extends layout
block content
h1.
User List
ul
each user, i in userlist
li
a(href="/viewuser/id/#{user._id}")=user.username
This:
a(href="/viewuser/id/#{user._id}")=user.username
Gives me:
Dhara
Now I don't know what route should be there for view details on click of the link and how to get selected record data for view screen.
I use a clear and distributed stack MEAN.js, with a yeoman constructor that will help you to build secure and good-practice programming applications.
This is the way I get a concrete user data. It´s a little more spread than your code but it´s clear.
Hope it helps!
routes.js
app.use('/api/users', require('./api/user'));
api/user/index.js
var controller = require('./user.controller');
router.get('users/:id', controller.show);
user.controller.js:
// Get a single user
exports.show = function(req, res) {
User.findById(req.params.id, function (err, user) {
if(err) { return handleError(res, err); }
if(!user) { return res.send(404); }
return res.json(user);
});
};
then I´ll call for a user with an url like users/xxxxxx where xxxx is the user id. Then if you want to do it like /viewuser/id/xxxxxx you will need to change the route like this:
api/user/index.js
var controller = require('./user.controller');
router.get('viewuser/id/:id', controller.show);
user.controller.js:
// Get a single user
exports.show = function(req, res) {
User.findById(req.params.id, function (err, user) {
if(err) { return handleError(res, err); }
if(!user) { return res.send(404); }
return res.json(user);
});
};
maybe you need to specify the view in your app server file
app.get('/userlist', function(req, res){
res.render('userlist', {
title: 'Your_Title'
});
});
I hope to be helpful!
I am new in Node Js and trying to learn it. I am currently follow this tutorial: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ but its incomplete.
I want, if I click on any user from the list of users, it will take me to new page and show the record in form for update. I don't know how to send data onclick, find the record from the db and show it inside a form to update.
Here is the index file with all the functions:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/*Get Hello world page*/
router.get('/helloword', function(req, res){
res.render("Helloworld", {title:'Hello, World!'});
});
/*Get UserList*/
router.get('/userlist', function(req, res){
var db = req.db;
var collection =db.get('usercollection');
collection.find({}, {}, function(e, docs){
res.render('userlist',{
"userlist": docs
});
});
});
/*Get New User Page*/
router.get('/newuser', function(req, res){
res.render('newuser',{title: 'Add New User'})
});
/* POST to Add User Service */
router.post('/adduser', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert({
"username" : userName,
"email" : userEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// And forward to success page
res.redirect("userlist");
}
});
});
module.exports = router;
Thanks in advance please help me for guidance
It looks like you want to use findAndModify (docs)
Using your code you could implement an update route like so.
router.post('/user/:userId', function (req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
collection.findAndModify(
{_id: req.query.userId}, // query
[['_id', 'asc']], // sort order
{
$set: {
"username": userName,
"email": userEmail
}
}, // replacement
{}, // options
function (err, object) {
if (err) {
console.warn(err.message); // returns error if no matching object found
} else {
console.dir(object);
}
});
});
However this does not have any validation to make sure that the user has the correct permissions to update this, make sure you add something like the query
{$and: [{_id: req.query.userId}, {createdBy: req.user}]}
I have a node js/express.js server and I am attempting to create a login function for my website using passport.js. I am NOT using MongoDB to store user info. Instead, I want to use my own AmazonAWS RDS MySQL instance as my database. This means I cannot use Mongoose.
As a result, I need to query for users without Mongoose to verify their credentials in Passport.js. My RDS instance has a table called Users that contains users with just the userName and password. Each record (user) in the table is also assigned its own unique usersObjectID number. I am attempting to query the users based on the user-name that the end-user will input into the login form and matching that user-name with a record in the table.
This is my server-side code:
var connection = mysql.createConnection(
{
//database connection info
}
connection.connect(function(error)
{
if(error)
{
console.log('MySQL error: '+error);
}
else
{
console.log('Successfully connected to MySQL database');
}
});
passport.use(new LocalStrat({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
//query user from DB
var usersObjectID = -1;
var tableLength = connection.query("select count(*) from Users");
console.log("this is the length of the table: "+tableLength);
for(var i = 0; i < tableLength; i++)
{
if(connection.query("select userName from Users where Users.usersObjectID = '"+i+"'") == username)
{
console.log(connection.query("select userName from Users where Users.usersObjectID = '"+i+"'"));
usersObjectID = i;
}
}
if(usersObjectID == -1)
{
//user not found
return done(null, false, {message: "The user is not exist"});
console.log("user does not exist");
}
else if(usersObjectID != -1 && connection.query("select userName from Users where Users.usersObjectID = '"+usersObjectID+"'") != connection.query("select password from Users where Users.usersObjectID = '"+usersObjectID+"'"))
{
// if password does not match
return done(null, false, {message: "Wrong password"});
console.log("password incorrect");
}
else
{
// if everything is OK, return null as the error
// and the authenticated user
return done(null, user);
console.log("successfully logged in");
}
}
));
This is my post method:
app.post('/login', function (req, res, next) {
var uname = req.body.username;
var pass = req.body.password;
var rem = req.body.remember_me;
console.log(uname+", "+pass+", "+rem);
// ask passport to authenticate
passport.authenticate('local', function(err, user, info) {
if (err) {
// if error happens
return next(err);
console.log("err");
}
if (!user) {
return res.redirect('/login');
console.log("!user");
}
// if everything's OK
req.logIn(user, function(err) {
if (err) {
return next(err);
}
console.log("ok");
return res.redirect('/');
});
})(req, res, next);
});
Here are my questions:
When I query
var tableLength = connection.query("select count(*) from QCBIMS.Users");
console.log("this is the length of the table: "+tableLength);
I get this result:
this is the length of the table: [object Object]
Why?
Would this be a good way to go about using an RDS instance for my user info and login function?
Encountered the same problem and solved it using the FF steps:
Use alias in the SELECT STATEMENT, like: "SELECT COUNT(*) AS total from QCBIMS.Users" Note: Using alias will make it easier to find it later
Select the first [key:value] pair from list & stringify as JSON: let resultStr=JSON.stringify(tableLength[0]) Note: I Used 'tableLength' from the query above. After stringify, result can be like
this: [{"total":"1541"}]
parse result as JSON: let itemPair = JSON.parse(resultStr)
get value using the 'alias' from SQL query: let value = itemPair[0].total
IF YOU WANNA SEE THE CONTENT OF THE [object Object], you can do this:
Object.keys(queryResult).forEach(function (key) {
console.log(JSON.stringify(queryResult[key]));
});
Why not use the query following way
connection.query('select count(*) as total from Users',function(err,rows){
var tableLength = rows[0];
// do the other stuff here
});
try
const count = rows.item(0)["count(*)"];
I want to have login/register function in my expressJS API.
So now im just inserting password and email into my database, i want this function to first check if user with this email is already in database - if yes, send response that user is logged.
If not, just insert him to database.
Is it possible to handle some errors in here?
I already have it:
exports.login = function(req, res){
var email = req.body.email;
var pwd = req.body.pass;
db.collection('users', function(err, collection) {
collection.insert({login:email, password: pwd}, {safe:true}, function(err, result) {
res.send("OK");
});
});
};\
and dont know what's next.
You can first try to find the user in your database. Assuming email is unique;
exports.login = function(req, res){
var email = req.body.email;
var pwd = req.body.pass;
db.collection('users', function(err, collection) {
if (err) return res.send(500, err);
collection.findOne({login:email}, function(err, user) {
// we found a user so respond back accordingly
if (user) return res.send('user logged in');
collection.insert({login:email, password: pwd}, {safe:true}, function(err, result) {
if (err) return res.send(500, err);
res.send("OK");
});
});
});
};
notice the return's before the res.send calls when handling errors.