How to fix the node.js code to check for login - mysql

I am new to node js and dont know why is this returning the false value always. I have form made in html that sends post request then the app.js calls login.js function and checks the database
I tried to manually input with 2 var and it works but when using the form it doesnt.
app.post('/login', urlencodedParser, function (req, res) {
var check = require('./js/login.js');
var username = req.body.username;
var password = req.body.password;
if(check([username,password]) == true){
console.log('fine');
res.render('index');
}
else{
console.log('get lost');
res.render('login');
}
});
This is the app.js code thet calls the login.js but the page doesnt render also even if the returned value is incorrect.
var check = function(arr){
var con = require(__dirname + '/database.js');
var login_check = false;
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM users WHERE (name = ?) AND (password = ?)", [arr[0], arr[1]], function (err, result, fields) {
if (err) throw err;
if(result)
{
login_check = true;
}
});
});
return login_check;
};
module.exports = check;

Because of your con.query function is asynchronous, so the return of function will always be false by default (it returns before executing check). Another way, you can try to use callback function as my suggestion code below:
app.post("/login", urlencodedParser, function(req, res) {
var check = require("./js/login.js");
var username = req.body.username;
var password = req.body.password;
var checkCallback = function (isLogin) {
if (isLogin) {
console.log("fine");
res.render("index");
} else {
console.log("get lost");
res.render("login");
}
}
check([username, password], checkCallback);
});
// -----------------------------
// login.js
var check = function(arr, callback) {
var con = require(__dirname + "/database.js");
var login_check = false;
con.connect(function(err) {
if (err) throw err;
con.query(
"SELECT * FROM users WHERE (name = ?) AND (password = ?)",
[arr[0], arr[1]],
function(err, result, fields) {
if (err) throw err;
if (result) {
login_check = true;
callback(true); // Call the callback function here after checking is done
}
}
);
});
return login_check;
};
module.exports = check;

Related

MYSQL length of results undefined

*throw err; // Rethrow non-MySQL errors
^
TypeError: Cannot read property 'length' of undefined*
db.js:
function validateUser(username, password) {
var sql = "SELECT * FROM users WHERE username = ? AND password = ?";
var values = [[username, password]];
con.query(sql,[values], function(err, results) {
if (results.length > 0){
return true;
}
else return false;
})
}
server.js:
app.post('/auth', function(req,res) {
console.log('form submitted');
if(db.validateUser(req.body.username,req.body.password)){
console.log('login successful');
}
res.status(200);
res.redirect(URL);
});
First please don't save passswords as plain text.
for example https://cdnjs.com/libraries/jsSHA
For your code:
function validateUser(username, password) {
var sql = "SELECT * FROM users WHERE username = ? AND password = ?";
var values = [username, password];
con.query(sql,values, function(err, results) {
if (results.length > 0){
return true;
}
else return false;
})
}

AWS Lambda stops execution in the middle of the code

I am trying to trigger csv file upload in s3 and insert the data from the file to database using lambda.
Most of the times code executes successfully if i run the code back to back in couple of seconds gap.
But sometimes the problem i face is the code stops execution at console console.log('about to get the data'); and ignore rest of the code and sometimes mysql connection gets time out.
I can find that the problem occurs only when i test the lambda code with more than 20 seconds of gap. So, i guess this is a cold start problem.
I don't want to miss even a single s3 trigger. So, i need help to find flaw in my code that is causing this problem.
const AWS = require('aws-sdk');
const s3 = new AWS.S3({region: 'ap-south-1', apiVersion: '2006-03-01'});
var mysql= require('mysql');
var conn = mysql.createPool({
connectionLimit: 50,
host: 'HOST',
user: 'USER',
password: 'PASSWORD',
database: 'DATABASE'
})
async function mainfunc (event, context, callback) {
console.log("Incoming Event: ", JSON.stringify(event));
const bucket = event.Records[0].s3.bucket.name;
const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
const params = {
Bucket: bucket,
Key: filename
};
console.log('about to get the data'); //Code stops here some times
return await getresult(params);
};
async function getresult(params){
var result = await s3.getObject(params).promise();
var recordList = result.Body.toString('utf8').split(/\r?\n/).filter(element=>{
return element.length> 5;
})
recordList.shift()
var jsonValues = [];
var jsonKeys = result.Body.toString('utf8').split(/\r?\n/)[0]
recordList.forEach((element) => {
element = element.replace(/"{2,}/g,'"').replace(/, /g,"--").replace(/"{/, "{").replace(/}"/, "}").replace(/,/g, ';').replace(/--/g,', ').split(';');
jsonValues.push(element)
});
var lresult = await query(jsonKeys, jsonValues);
return lresult;
}
async function query(jsonKeys, jsonValues){
var qresult = await conn.getConnection(function(err, connection) {
if (err){
console.log(err,'------------------------------------');// Sometimes i get Sql Connection timeout error here
} else {
console.log("Connected!");
var sql = "INSERT INTO reports ("+jsonKeys+") VALUES ?";
connection.query(sql, [jsonValues], function (err, result) {
if (err){
console.log(err);
connection.release()
return err;
} else {
console.log("1 record inserted");
console.log(result);
connection.release()
return result;
}
});
}
})
}
exports.handler = mainfunc
I have solved the issue by using promise in the "query" function
function query(jsonKeys, jsonValues){
return new Promise(function(resolve, reject) {
conn.getConnection(function (err, connection) {
if (err) {
console.log(err, '------------------------------------');
}
else {
console.log("Connected!");
var sql = "INSERT INTO principal_reports (" + jsonKeys + ") VALUES ?";
connection.query(sql, [jsonValues], function (err, result) {
if (err) {
console.log(err);
connection.release();
reject(err)
}
else {
console.log("1 record inserted");
console.log(result);
connection.release();
resolve(result)
}
});
}
})
})
}
and changed the code
var lresult = await query(jsonKeys, jsonValues);
to
var lresult = await query(jsonKeys, jsonValues).then(data =>{
return data;
}).catch(error =>{
return error;
});

Node.js - MySQL API, multi GET functions

I'm new in making API. I use Node.js and MySQL.
The fact is I have two GET function to get all users and one to get user by ID.
Both function are working when they are alone implemented. If both of them are implemented the function to get all user try to enter in the function to get user by ID so the API crash.
So here is my model users.js
var connection = require("../connection");
function Users()
{
//GET ALL USERS
this.get = function(res)
{
console.log('Request without id');
connection.acquire(function(err, con)
{
con.query('SELECT * FROM users', function(err, result)
{
con.release();
if (err)
res.send({status: 1, message: 'Failed to get users'})
else
res.send(result);
});
});
}
//GET USER BY ID
this.get = function(id, res)
{
console.log('Request with ID');
connection.acquire(function(err, con)
{
if (id != null)
{
con.query('SELECT * FROM users WHERE id = ?', id, function(err, result)
{
con.release();
if (err)
res.send({status: 1, message: 'Failed to find user: ' + id});
else if (result == "")
res.send({status: 1, message: 'Failed to find user: ' + id});
else
res.send(result);
});
}
});
}
And here is the routes.js
var users = require('./models/users');
module.exports = {
configure: function(app) {
app.get('/users/', function(req, res) {
users.get(res);
});
app.get('/users/:id/', function(req, res) {
users.get(req.params.id, res);
});
Do you have any idea why ?
Thanks for help :)
You can't have two functions with the same name in the same scope.
You have to rename your functions
/**
* Get all users
*/
this.get = function(res) {...}
/**
* Get user by id
*/
this.getById = function(id, res) {...}
Or you can have one function and check if an id is provided
this.get = function(id, res) {
if ( Number.isInteger(id) ) {
// return the user
} else {
res = id;
// return all users
}
}

error: POST http://localhost:3000/api/createProductCategory 500 (Internal Server Error)

I am trying to insert data into a table using POST method for that I have a angular service function
angular.module("productCategoryModule")
.factory("productCategoryService",productCategoryService);
productCategoryService.$inject = ['$http'];
function productCategoryService($http){
return {
createProductCategory:function(productCategory){
console.log("createProductCategory in service called",productCategory);
return $http.post('/api/createProductCategory',
{
categoryName:productCategory.categoryName,
details:productCategory.categoryDetails
}
);
},
getAllProductCategories:function(){
return $http.get('/api/getAllProductCategory');
}
}
}
and at server side I have
function productCategoryRouteConfig(app){
this.app = app;
this.routeTable = [];
this.init();
}
productCategoryRouteConfig.prototype.init = function(){
var self = this;
this.addRoutes();
this.processRoutes();
}
productCategoryRouteConfig.prototype.processRoutes = function(){
var self = this;
self.routeTable.forEach(function(route){
if(route.requestType == 'get'){
//console.log("requestType",route.requestType)
self.app.get(route.requestUrl,route.callbackFunction);
} else if(route.requestType == 'post'){
//console.log("requestType",route.requestType);
self.app.post(route.requestUrl,route.callbackFunction);
} else if(route.requestType == 'delete'){
}
});
}
productCategoryRouteConfig.prototype.addRoutes = function(){
var self = this;
self.routeTable.push({
requestType: 'get',
requestUrl: '/createProductCategory',
callbackFunction: function(req, res){
res.render('createProductCategory',{title:'Create Product Category'});
}
});
self.routeTable.push({
requestType: 'post',
requestUrl: '/api/createProductCategory',
callbackFunction: function(req, res){
console.log("Post called");
//res.render('createProductCategory');
console.log("req.body",req.body);
var productCategoryDb = require('../database/productCategoryDb');
// console.log("productCategoryDb post",productCategoryDb);
// console.log("hello from createProductCategory post");
// console.log("req.body",req.body);
// productCategoryDb.productCategoryDb.createProductCategory(req.body, function(status){
// if(status)
// res.json(status);
// console.log(status);
// });
}
});
self.routeTable.push({
requestType: 'get',
requestUrl: '/viewProductCategory',
callbackFunction: function(req, res){
res.render('viewProductCategory',{title:'View Product Category'});
}
});
self.routeTable.push({
requestType: 'get',
requestUrl: '/api/getAllProductCategory',
callbackFunction: function(req, res){
console.log("hello from getAllProductCategory");
var productCategoryDb = require('../database/productCategoryDb');
console.log("productCategoryDb",productCategoryDb);
// productCategoryDb.productCategoryDb.getAllProductCategories(
// function (productCategories){
// console.log("productCategories",productCategories);
// res.json({productCategories : productCategories});
// }
// );
}
});
}
module.exports = productCategoryRouteConfig;
when I click on the button on client side I get this error
POST http://localhost:3000/api/createProductCategory 500 (Internal Server Error)
I am using Node express mysql and angular.
There are three files in me database folder.
1.connectionString.js
var mysqlConnectionString = {
connectionString:{
host:'localhost',
user:'root',
password:'root',
database:'vidzy'
}
}
//module.exports = mysqlConnectionString;
exports.mysqlConnectionString = mysqlConnectionString;
2.connection.js
var mysql = require('mysql');
var mysqlConnectionString = require('/home/ep-3/node-express/yt_tutorial/database/connectionString.js');
var connectionStringProvider = {
getSqlConnection:function(){
var connection = mysql.createConnection(mysqlConnectionString.mysqlConnectionString.connectionString);
connection.connect(function(err){
if(err){
throw err;
} else{
console.log("connection was successful");
}
});
return connection;
},
closeSqlConnection:function(currentConnection){
currentConnection.end(function(err){
if(err){
throw err;
} else{
console.log("Disconnected");
}
})
}
}
exports.connectionStringProvider = connectionStringProvider;
3.productCategoryDb.js
var connectionProvider = require('/home/ep-3/node-express/yt_tutorial/database/connection.js');
var productCategoryDb = {
createProductCategory : function(productCategory, onSuccessful){
var insertStatement = 'INSERT INTO productcategory SET?';
var category = {
categoryName : productCategory.categoryName,
Details : productCategory.details,
isValid : productCategory.isValid,
CreatedDate : new Date()
}
var connection = connectionProvider.connectionStringProvider.getSqlConnection();
if(connection){
connection.query(insertStatement, category, function(err, result){
if(err){
console.log(err);
}
onSuccessful({status : 'Successful'});
console.log(result);
});
connectionProvider.connectionStringProvider.closeSqlConnection(connection);
}
},
getAllProductCategory : function(callback){
var connection = connectionProvider.connectionStringProvider.getSqlConnection();
var selectStatement = 'SELECT * FROM productcategory';
if(connection){
connection.query(selectStatement, function(err, rows, fields){
if(err){ through err; }
console.log(rows);
callback(rows);
});
}
}
}
exports.productCategoryDb = productCategoryDb;
Are you sure you have included the module body-parser.
It seems the code you posted here to be the same as the tutorial I have been following.
Your code seems to be fine except I don't know what your code in app.js looks like.
I have verified that I get the console response for req.body as undefined when I comment out the module body-parser.
I got the same error but in my case there was a node-modules function that increments id for each POST I made and i forgot to add id in my DTO..and now it's working; maybe it's not your case since u are using mysql but I'll post the answer anyway, maybe some1 will resolve his error thank to this help

Creating a new model doesn't work - no error

i am using node-orm2 with mysql in my project. I have already created the database tables, and i can query/find data in my DB. However, when i want to insert new data, nothing happens - no error in the callback, nothing.
Here is the relevant code:
Model class:
module.exports = function (orm, db) {
var Comment = db.define('comment', {
body: {type: 'text'}
});
};
Index.js in the model folder:
var orm = require('orm');
var settings = require('../config/settings');
var connection = null;
function setup(db, cb) {
require('./comment')(orm, db);
return cb(null, db);
}
module.exports = function (cb) {
if (connection) return cb(null, connection);
orm.connect(settings.database, function (err, db) {
if (err) return cb(err);
connection = db;
db.settings.set('instance.returnAllErrors', true);
db.settings.set('connection.debug', true);
setup(db, cb);
});
};
Controller:
var orm = require('orm');
exports.create = function(req, res){
var testcomment = {};
testcomment.body = "test comment";
req.models.comment.create(testcomment, function (err, message) {
if (err) return console.log(err);
return res.send(200, message);
});
};
Environment.js
var path = require('path');
var express = require('express');
var settings = require('./settings');
var models = require('../models/');
var logger = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
module.exports = function (app) {
app.use(express.static(path.join(settings.path, 'public')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride());
app.use(function (req, res, next) {
models(function (err, db) {
if (err) return next(err);
req.models = db.models;
req.db = db;
return next();
});
})
};
Settings.js:
var path = require('path');
var settings = {
path : path.normalize(path.join(__dirname, '..')),
port : process.env.NODE_PORT || 3001,
database : {
protocol : "mysql",
host : "localhost",
port : "3306",
database : "taxidatabase",
user : "root",
password : "admin"
}
};
module.exports = settings;
I basically followed the pattern in the example application in node-orm2 - but it doesn't work. Any idea, why?
Thanks!
Before adding anything to table you need to sync the DB at least once after you define the models in order to create the tables:
var models = require('../app/models/');
models(function (err, db) {
if (err) throw err;
db.sync(function (err) {
if (err) throw err;
console.log('Done!');
});
});
Or maybe syncing the comment model will do:
var orm = require('orm');
exports.create = function(req, res){
var testcomment = {};
testcomment.body = "test comment";
req.models.comment.create(testcomment, function (err, message) {
if (err) return console.log(err);
return res.send(200, message);
});
req.models.comment.sync(function (err) {
if (err) throw err;
console.log('Done!');
});
};