NodeJS Pass parameter to mysql query - mysql

I am building nodeJS application .I want to pass parameter to my query statement .Below is the module that processes what I am looking for but unfortenately the insertion succeeds whithout the value of my parameter I passed to my query.when I check it to my database new row is inserted but with values of null.
Below is my database table capture for this app
app.post('/login',function(req, res){
var name = req.session.name ;
var pass = req.session.pass;
var mail = req.session.mail ;
con.connect(function(err){
con.query("INSERT INTO register values(null, ?, ?, ?)",[name,mail,pass],
function(err,result){
if(err) { return console.log("Error when registration");}
console.log("registration succeeded + query");
});
});
});
thanks in advance
NOTE : No issue with database connection

you have to use req.bosy instead os req.session. For that you need to require body-parser and configure it like
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
and in your code, you have to replace req.session.name with req.params.name like that. Please try this. Hope this helps. Thanks

Request object does not have session property. I think you may be looking for body property.

app.post('/login',function(req, res){
//params
const name = req.body.name ;
const pass = req.body.pass;
const mail = req.body.mail ;
// sql syntax
const syntaxSQL = "INSERT INTO register (name,pass,mail) values ('"+name+"','"+pass+"','"+mail+"')" ;
con.connect(function(err){
con.query(syntaxSQL, // <== use your previously built query here
function(err,result){
if(err) { return console.log("Error when registration");}
console.log("registration succeeded + query");
});
});
});

Related

Save Query result into Variable Alexa Skills Json

I needed a DB for an alexa app, so I set up and and it INSERTS nicely, but when im trying to SELECT and save it to a variable the values saved to the variable are [Object Object] instead of wanted value, I know it can be async problem or parsing problem but i just cant fix the code, some help would be cool,
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& Alexa.getIntentName(handlerInput.requestEnvelope) === 'buscaIntent';
},
handle(handlerInput) {
const mysql = require('mysql');
const connection = mysql.createConnection
({
host: 'remotemysql.com',
user: 'RBb34534sd',
password: 'xxxxxxxxx',
database: 'RBsdfewrg'
});
var stat = connection.query('SELECT `spe` FROM `prueba` WHERE `nombre` LIKE "raichu" limit 1', function (err, result, fields) {
if (err) throw err;
console.log(result);
return result[0];
});
connection.end();
return handlerInput.responseBuilder
.speak("Busc " + stat)
.reprompt("reprompt buscar")
.getResponse();
}
}; ```
The issue is that you're not waiting for your database query to complete before sending your response to the Alexa service. Requests in node.js are non-blocking, meaning you either need to nest the request with a callback, or leverage Promises / async-await patterns so that the SQL query is processed before the function is fully executed.
You can read more on converting the built-in library for SQL connections to support Promises here, or use a library like this that already has a wrapper in place.
In either scenario, the end result would be refactored to something like this:
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& Alexa.getIntentName(handlerInput.requestEnvelope) === 'buscaIntent';
},
async handle(handlerInput) {
const mysql = require('mysql2/promise');
const connection = await mysql.createConnection
({
host: 'remotemysql.com',
user: 'RBb34534sd',
password: 'xxxxxxxxx',
database: 'RBsdfewrg'
});
var stat = await connection.execute('SELECT `spe` FROM `prueba` WHERE `nombre` LIKE "raichu" limit 1', function (err, result, fields) {
if (err) throw err;
console.log(result);
return result[0];
});
return handlerInput.responseBuilder
.speak("Busc " + stat)
.reprompt("reprompt buscar")
.getResponse();
}
Another article describing async calls for Alexa requests here.
I think the query is returning an object you can't keep the object in speech. Check what's inside the object and if you have a field that you want inside that object then access by stat.YourField.

Node.JS and MySQL - queries lock up and execute extremely slowly

I am getting strange behavior using Node.JS and MySQL with this driver - https://github.com/mysqljs/mysql
Essentially, I have a button on the frontend that triggers an app.get that makes a query in the database and I can happily use the results in my backend.
This works nicely, until I press the button 4-5 times in a second, where as the queries lock up and I have to wait for 2-3 minutes until they continue executing. I have a similar write function that behaves the same way.
Is it possible this is a problem, because I'm trying to execute the exact same query asynchronously? I.e. do I have to limit this from the front end or is it a backend problem?
Any ideas on how to debug what exactly is going on?
// database.js
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 100,
host : 'localhost',
user : 'secret',
password : 'secret',
database : 'mydb'
});
exports.getConnection = function(callback) {
pool.getConnection(function(err, connection) {
callback(err, connection);
});
};
// dbrw.js
var con = require('../config/database');
function read(id, done) {
con.getConnection(function(err, connection){
if(!err){
connection.query("SELECT * FROM users WHERE id = ?",[id], function(err, rows) {
connection.release();
if (err)
done(err);
if (rows.length) {
console.log("rows " + JSON.stringify(rows));
done(rows[0].progress);
};
});
}
else {
console.log(err);
}
});
}
exports.read = read;
// routes.js
var dbrw = require('./dbrw.js');
app.get('/read', isLoggedIn, function(req, res) {
dbrw.read(req.user.id, function(result) {
console.log(result);
});
});
// Frontend - angular app.js
$scope.tryread = function() {
$http.get('/read');
}
Thanks in advance for any input.
I see a few issues:
function read(id, done) {
con.getConnection(function(id, connection){...}
}
Notice how you overwrite the id passed to read by giving that same name to an argument of the callback to getConnection.
Also, your Express route doesn't actually end the request by sending back a response, which will make your browser time out the connection. At some point, it will even refuse to send more requests because too many are still pending.
So make sure to end the request:
app.get('/read', isLoggedIn, function(req, res) {
dbrw.read(req.user.id, function(result) {
console.log(result);
res.end(); // or `res.send(result)`
});
});
And a tip: you should use the callback calling convertion for Node, where the first argument represents an error (if there is any) and the second argument represents the return value.

Node JS Error: write after end

In the following code, I am trying to retrieve data from MySQL database and show them to a user by using response write. The error that I got is Error: write after end:
var http = require("http");
var mysql = require('mysql');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/Search.html', function (req, res) {
res.sendFile( __dirname + "/" + "Search.html" );
})
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : 'somepass',
database : 'SocialQuery',
}
);
connection.connect();
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
SearchType:req.body.SearchTypes,
Term:req.body.term
};
//var vas = JSON.stringify(response);
var search = req.body.SearchTypes;
var term = req.body.term;
var query = connection.query('Select * from ?? where Lable = ?', [search, term], function(err, rows) {
res.write(rows);
});
console.log(query.sql);
res.end();
})
//}).listen(8081);
http.createServer(app).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
I changed res.write(rows); to res.end(rows); but didn't work. Can someone help me solving this problem.
The problem is that MySQL queries are asynchronous in node.js. so, the result won't be in the variable query, but retrieved in the callback, to the variable rows. So what happens is that res.end() is called, and then the callback returns and res.write() is called, so it's called after end().
You are doing an Asynchronous call when fetching data from database. res.write() is inside callback function so before fetching data it would call res.end() and res.write() will be called after the data has been fetched. That's why you are getting Error: write after end . You can use res.end() in the same callback function.
var query = connection.query('Select * from ?? where Lable = ?', [search, term], function(err, rows) {
res.write(rows, function(err){
res.end();
});
});
Now the res.end() function will be called after the write process has been done.
It worked after I made two changes:
var query = connection.query('Select * from ?? where Lable = ?', [search, term], function(err, rows) {
console.log(rows);
res.write(JSON.stringify(rows));
res.end();
});
First, I moved res.end(); inside the connection.query part.
Second, instead of writing rows only, I changed to res.write(JSON.stringify(rows));

Knex NodeJS and inserting into the database

I am new to nodejs and was trying to set up an API server, here is my first attempt. I wanted to use mysql instead of mongo db.
My problem is that 'knex('user').insert({email: req.body.email});' doesn't seem to want to save to the database.
var dbConfig = {
client: 'mysql',
connection: {
host : 'localhost',
user : 'root',
password : '',
database : 'db_nodeapi'
}
};
var express = require('express'); // call express
var bodyParser = require('body-parser'); // call body-parser
var knex = require('knex')(dbConfig); // set up database connection
var app = express(); // define our app using express
app.use(bodyParser.urlencoded({ extended: true })); // configure app to use bodyParser()
app.use(bodyParser.json()); // this will let us get the data from a POST
var router = express.Router(); // get an instance of the express Router
router.use(function(req, res, next) { // middle ware for authentication
console.log(' -Logging- ');
next(); // continue to next route without stopping
});
router.get('/', function(req, res) { // listen for a post on root
res.json({ message: ' -Success- ' });
});
router.route('/user') // set up user route
.post(function(req, res) { // listen for a post on user
console.log(' -Post -'); // report a post
knex('user').insert({email: req.body.email}); // insert user into user table
res.json({ success: true, message: 'ok' }); // respond back to request
});
app.use('/api', router); // register routes beginning with /api
var port = process.env.PORT || 8080; // set server port number
app.listen(port); // setup listener
console.log('Magic happens on port ' + port); // report port number chosen
Problem is I can't get knex to add to the database!
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL,
`email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
Here is the database
The problem in your code is that you are missing the ".then" statement, which causes the actual execution of the code.
knex('user').insert({email: req.body.email})
.then( function (result) {
res.json({ success: true, message: 'ok' }); // respond back to request
})
That should work. Since knex.js's insert function is a promise, you need to call .then() to actually call it.
Someone has already given a solution. I am here to talk about why adding a then statement can solve this problem.
In fact, then, catch statement are both ok. Please refer to the knex documentation(http://knexjs.org/#Interfaces-then), which mentions:
Coerces the current query builder chain into a promise state.
So select, update, insert, etc. are just the query statement builder, you have to use then or catch to convert it to promise state.
Examples are as follows:
knex('user').insert({email: req.body.email}) //not working
knex('user').insert({email: req.body.email}).then(()=>{}) //working
knex('user').insert({email: req.body.email}).catch(()=>{}) //working
.then(()=>{
knex('user').insert({email: req.body.email}) //not working
knex('user').insert({email: req.body.email}).then(()=>{}) //working
knex('user').insert({email: req.body.email}).catch(()=>{}) //working
return knex('user').insert({email: req.body.email}) //working
})
Solved try this I think there should be some after hook in knex where we can do this automatically but till then this should works.
knex('users')
.insert(data)
.then(async () => {
const result = await knex.raw('select LAST_INSERT_ID() as id');
const id = result[0][0].id;
const user = await knex.from('users').where('id', id);
res.json({ success: true, message: 'ok', user: user[0] });
});
Had similar issue once, try this:
//...
router.route('/user').post(function(req, res) {
knex('user').insert({email: req.body.email}).then(function(ret){
res.json({ success: true, message: 'ok'/*,ret:ret*/});
});
});
//...
So I was seen the above solutions all are good if you want to add more than one field without mentioning each field you can go with the below syntax:
knex('students').insert(req.body).then((newUser) => {
res.json({newUser});
}).catch((e)=>console.log(e));
So here your input tag names should be equivalent to the database table field names

object is not a function in mysql db using with nodejs

I'm following the tutorial but first i got this error:
deprecated: connect() is now done automatically
I changed my code but after that im faceing this error:
object is not a function at Client.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)
and I've no idea as I'm new to nodejs and mysql so kindly help me out!!
here is my code:
var Client = require('mysql').createClient({'host':'localhost','port':'3306','user':'root', 'password':''});
var client = new Client();
console.log('Connecting to mysql..');
ClientConnectionReady(client);
ClientConnectionReady = function(client){
client.query('USE login',function(err,result){
if(err){
console.log('cant create Table Error:'+ err.message);
client.end();
return;
}
ClientReady(client);
};
ClientReady = function(client){
var values = ['fahad','tariq'];
client.query('INSERT into Login SET username = ?, password = ?',values,
function(err,result){
if(err){
console.log("ClientReady Error:" + error.message);
client.end();
return;
}
console.log('inserted:'+result.affectedRows+'ros.');
console.log('Id inserted:'+ result.insertId);
});
GetData(client);
}
GetData = function(client){
client.query(
'SELECT * FROM Login',
function selectCb(err,result,fields){
if(err) {
console.log('Getdata Error'+err.message);
client.end();
return;
}
if(result.length>0) {
var firstResult = results[0];
console.log('username' + firstResult['username']);
console.log('password'+firstResult['password']);
}
});
client.end();
console.log('connection closed');
};
Not sure this is what's causing your specific message, but in ClientReady you're calling GetData before your INSERT has had a chance to execute; you should be doing it inside the callback from the INSERT.
UPDATE: Now that someone was kind enough to properly indent everything (hint: stuff that should be indented should begin with 4 spaces) it becomes clear that you have a similar problem in GetData(): you're calling client.end() before your callback has had a chance to execute. Thus your SELECT callback is trying to use a closed MySQL connection, which is probably causing the failure.