get a callback from a seperate file in node js - javascript

I have two file in my node js app server.js and database.js
//server.js
var db = require('./database.js');
var express = require('express');
var app = express();
var server = app.listen(8081, '000.00.00.000',function(){
var host = server.address().address;
var port = server.address().port
console.log('App listening');
})
app.get('/',function(req,res){
res.end("Hello Jamian");
})
app.get('/insertuser',function(req,res){
console.log("insert user called")
var result = new db.insertUser();
console.log("result " + result)
});
and
//database.js
var mysql = require('mysql');
var con = mysql.createConnection({
host:"localhost",
user:"0000",
password:"0000",
database: "aaaa"
});
con.connect(function(err){
if(err) throw err;
console.log("DB Connected");
});
module.exports = {
insertUser: function () {
console.log("module exported");
var SQL_insert_user = "insert into users(username,useremail,usermobile,userpassword,activetoken) values('darren','darren#yahoo.in','980000000','password','ASKDO5615F')";
con.query(SQL_insert_user,function(err,result){
if(err) throw err;
console.log("data inserted");
return result;
});
},
bar: function () {
console.log("bar called")
}
};
I need a callback from the insertUser function in database.js so i can call a res.end("data inserted"). however it seems con.query is going async, hence I am getting a blank value when I try to log result in server.js from get/insertuser in server.js
data inserted
insert user called
module exported
result {}
data inserted

Use promises. Either native or from a library.
Here's how you could do it with a promise:
insertUser: function(){
return new Promise(function(reject, resolve){
var SQL_insert_user = "insert into users(username,useremail,usermobile,userpassword,activetoken) values('darren','darren#yahoo.in','980000000','password','ASKDO5615F')";
con.query(SQL_insert_user,function(err,result){
if(err) reject(err);
else resolve(result);
});
});
},
Then you can use it your other file like this:
insertUser()
.then(function(result){
// do something with the result
})
.catch(function(err){
// Oh no! there was an error!
});

in your server js do
app.get('/insertuser',function(req,res){
console.log("insert user called")
var result = new db.insertUser(function(result) {
console.log("result " + result)
});
});
and in your database do
module.exports = {
insertUser: function (cb) {
console.log("module exported");
var SQL_insert_user = "insert into users(username,useremail,usermobile,userpassword,activetoken) values('darren','darren#yahoo.in','980000000','password','ASKDO5615F')";
con.query(SQL_insert_user,function(err,result){
if(err) throw err;
console.log("data inserted");
cb(result);
});
},
bar: function () {
console.log("bar called")
}
};

Related

TypeError: db.collection is not a function with user password restriction

I have a university project where I can ssh to a server that has a mongodb with fixed database/username/password. I imported a collection and now want to read it out with nodejs for testing. After starting it with node server.js it returns "Connected correctly to server" into console but then I get a TypeError: db.collection is not a function
What is wrong? Thanks
var MongoClient = require('mongodb').MongoClient;
const user = encodeURIComponent('x');
const password = encodeURIComponent('y');
const authMechanism = 'DEFAULT';
// Connection URL
const url = `mongodb://${user}:${password}#localhost:27017/database?authMechanism=${authMechanism}`;
MongoClient.connect(url, function(err, db) {
console.log("Connected correctly to server");//works
var cursor = db.collection('locations').find();//throws error
cursor.each(function(err, doc) {
console.log(doc);
});
});
Try this way:
var MongoClient = require('mongodb').MongoClient;
const user = encodeURIComponent('x');
const password = encodeURIComponent('y');
const authMechanism = 'DEFAULT';
// Connection URL
const url = `mongodb://${user}:${password}#localhost:27017/database?authMechanism=${authMechanism}`;
MongoClient.connect(url, function(err, db) {
if(err){
console.log("Connection failed");
}
else{
console.log("Connected correctly to server");
var cursor = db.collection('locations');//same error
cursor.find({}).toArray(function(err,docs){
if(err){
console.log("did'nt find any!")
}
else{
console.log(docs)
}
});
}
});
Got it working after all:
var MongoClient = require('mongodb').MongoClient;
const user = encodeURIComponent('x');
const password = encodeURIComponent('y');
const authMechanism = 'DEFAULT';
// Connection URL with and without authentication
const url = `mongodb://${user}:${password}#localhost:27017/database?authMechanism=${authMechanism}`;
//const url = `mongodb://localhost:27017/`;
MongoClient.connect(url, (err, db) => {
if(err) throw err;
console.log("connect works");
let database = db.db('database');
database.collection('users').find().toArray((err, results) => {
if(err) throw err;
results.forEach((value)=>{
console.log(value);
});
})
});

Passing variable from one js to another js file in nodejs

I'm just getting started with Nodejs, so please bear with me
I store my DB setting on the first JS, connect.js :
var mysql = require('mysql');
module.exports = function(connectDB) {
var connectDB = {};
connectDB.connection = mysql.createConnection({
//db params
});
connectDB.connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
return connectDB;
};
Then I stored my query in another JS file, lets call it dbManager.js :
var db = require('./connect')(connectDB);
var test_connection = connectDB.connection.query('SELECT * FROM `test`', function (error, results, fields) {
console.log(results);
});
exports.test = test_connection;
My goal is to pass the connection variable from connect.js to dbManager.js, so I could use it for running some queries.
The above code return an error, which said the variable is not passed successfully to dbManager.js :
ReferenceError: connectDB is not defined
Thanks in advance
The syntax error is because you cant define variables within an object literal using var.
e.g., you can't do the following,
var t = {
"r": 4,
var g = 5;
};
You can do this,
var t = {
"r": 4,
"g" : 5
};
And to access the properties of the object you can do,
console.log(t["r"]);
console.log(t.g);
In your code the problem is declaring a variable inside an object literal. Yo could do,
var connectDB = {};
connectDB.connection = mysql.createConnection({
//DB params
});
connectDB.connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connectDB.connection.threadId);
});
return connectDB;
Edit1 As per OP's comments,
connect.js:-
Changes- No need of the connectDB param, using module.exports functionality.
var mysql = require('mysql');
var connectDB = {};
connectDB.connection = mysql.createConnection({
//db params
});
connectDB.connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connectDB.connection.threadId);
});
module.exports = connectDB;
dbManager.js:-
var db = require('./connect');//removed the parameter
//use db variable to process queries as returned from the above require statement.
var test_connection = db.connection.query('SELECT * FROM `test`', function (error, results, fields) {
console.log(results);
});
exports.test = test_connection;
**you can do it like this
connection.js**
var mysql=require('mysql');
// Database Connection
var connection = mysql.createConnection({
host : hostname,
user :username,
password : password,
database : databasename,
multipleStatements:true
});
try {
connection.connect();
} catch(e) {
console.log('Database Connetion failed:' + e);
}
module.exports=connection;
**you can use this connection file in your dbmanager file like
this..**
var db = require('./connection.js');var test_connection =
connection.query('SELECT * FROM test', function(err,result) {
console.log(result);
});
Will something like this work for you? You can have a file that returns a connection object from the pool:
var mysql = require('mysql');
module.exports = function() {
var dbConfig = {...};
var database = mysql.createPool(dbConfig);
return {
getConnection: function(callback) {
// callback(error, connection)
database.getConnection(callback);
}
};
};
Wherever you need to use it, you can require it as follows:
var connector = require('./db-connector')();
Then use it like this:
connector.getConnection(function(error, connection) {
// Some code...
// Be sure to release the connection once you're done
connection.release();
});
This is how I store config data to pass around on my node server. I call it config.js and .gitignore it. I keep a sample copy called config.sample.js
let config = {};
config.mysql-host='localhost' || process.env.MYSQL_HOST;
config.mysql-user='me' || process.env.MYSQL_USER;
config.mysql-secret='secret' || process.env.MYSQL_SECRET;
config.mysql-database='my_db' || process.env.MYSQL_DB;
module.exports = config; //important you don't have access to config without this line.
To use it I would do the following.
const config = require('./config');
const mysql = require('mysql');
const connection = mysql.createConnection({
host: config.host,
user: config.user,
password: config.password,
});
connection.connect((err) => {
if(err) {
console.error(`error connecting: ${err.stack});
return;
}
console.log(`connected`);
});
const test_connection = connectDB.connection.query('SELECT * FROM `test`'(error, results, fields) => {
console.log(results);
});

in node.js with express req.session is undefined inside my require() module

I'm wondering why req.session.username is undefined in the tag >>>DOESNT WORK<<< while it does work in the tag >>>THIS DOES WORK<<< . I brought in req as an argument to my module but it seems I'm supposed to do something else? The /ajax route is accessed via a ajax call and it does set the session variable in >>>THIS DOES WORK<<<
//index.js file
var express = require('express');
var router = express.Router();
var app = express();
var functions = require('../public/javascripts/functions.js');
router.post('/ajax', function(req, res , next){
var username = req.param("username");
var password = req.param("password");
var operation = req.param("operation");
else if (operation === "validate")
{
async.series([
function()
{
functions.validate(username, password, req);
}
], function(err,result)
{
if (err)
return console.log(err);
console.log(result);
});
//req.session.username = "yaryar"; >>>THIS DOES WORK<<<
}
var strings = ["rad", "bla", "ska"]
console.log('body: ' + JSON.stringify(req.body));
console.log("AJAX RECEIVED");
res.send(strings);
});
module.exports = router;
functions.js file:
module.exports = {
validate: function(username, password, req) {
var url = 'mongodb://localhost';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
MongoClient.connect(url, function(err, db)
{
assert.equal(null, err);
console.log("Connected correctly to server.");
var cursor = db.collection('users').find({username : username});
cursor.each(function(err,doc,req)
{
assert.equal(err, null);
if (doc != null)
{
console.log("user found: " + doc.username);
req.session.username = "ttyy"; // >>>DOESNT WORK<<<
return true
}
else
{
console.log("user not found");
return false;
}
});
//db.close();
});
}
};
you're overwriting req by doing cursor.each(function(err,doc,req) change it to cursor.each(function(err,doc,arr) and it will work

Not able to insert data into sqlserver, nodejs

I have just made a simple program to display and insert data from a database(sql server 2008). My code does the display of data. I am unable to get data inserted. It shows no error in terminal or browser.
Here is my javascriptfile
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
var sql = require("mssql");
var config = {
user: 'pkp',
password: 'pkp',
server: 'PRAVEEN\\SQLEXPRESS',
database: 'myneww'
};
app.get('/process_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
console.log(req.query.first_name);
var res=request.query('insert into Mytab values(req.query.first_name ,req.query.last_name)');
});
});
app.get('/alldata', function (req, res) {
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Mytab', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Here is my html file
<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
I am able to get the values displayed in the console, means values are passed and retrieved from the form. But still not inserted into the database.
I'm not good in javascript, but I guess the line below is incorrect:
var res=request.query('insert into Mytab values(req.query.first_name ,req.query.last_name)');
It should be something like this.
var res=request.query('insert into Mytab values(' + req.query.first_name + ',' + req.query.last_name +')');
If not, you've got an idea.
First, you were not passing values properly to query and, secondly, you are not waiting for the record to insert. Add the callback that I added.
app.get('/process_get', function (req, res) {
//some code
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
console.log(req.query.first_name);
request.query('insert into Mytab values('+req.query.first_name+','+req.query.last_name+')', function(err, recordset) {
if (err) {
console.log(err);
return res.send('Error occured');
}
return res.send('Successfully inserted');
});
});
});
Update
Use transaction to commit changes.
app.get('/process_get', function (req, res) {
//some code
var sqlConn = new sql.Connection(config);
sqlConn.connect().then(function () {
var transaction = new sql.Transaction(sqlConn);
transaction.begin().then(function () {
var request = new sql.Request(transaction);
request.query('Insert into EmployeeInfo (firstName,secondName) values ('+req.query.first_name+','+req.query.last_name+')').then(function () {
transaction.commit().then(function (recordSet) {
console.log(recordSet);
sqlConn.close();
return res.send('Inserted successfully');
}).catch(function (err) {
console.log("Error in Transaction Commit " + err);
sqlConn.close();
return res.send('Error');
});
});
});
});
Forgive me, if there is any typo.

Cannot call method 'send' of undefined(response is undefined) in express js

I have tried to pass a variable from my index.html to the database(maildata.js) through app.js(server) and get the corresponding data
I am able to get the data from the database but couldnt send that back to the server(app.js)
app.js
var express = require('express');
var maildata= require('./maildata');
var app = express();
app.configure(function(){
app.use(express.bodyParser());
});
app.get('/', function(request, response){
response.sendfile(__dirname + '/mailbox.html');
});
app.post('/mailboxpost',function(request, response) {
var input=request.query.search;
var result=maildata.getMailData(input);
response.send(result);
response.end();
});
app.listen(8888);
console.log('Server is running on port 8888');
maildata.js
exports.getMailData=function(data,response) {
var stop_name= data;
connection.query("select stop_name,stop_comment from stoplist where stop_name= '"+stop_name+"' limit 1",function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString1= JSON.stringify(rows);
connection.query("select mailbox_sequence_no from stoplist where stop_name= '"+stop_name+"'",function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString2 = JSON.stringify(rows);
connection.query("select party_head from stoplist where stop_name= '"+stop_name+"'", function(err, rows) {
if (err) {
console.log('error in fetching ' + err);
}
else{
var jsonString3 = JSON.stringify(rows);
var result=jsonString1+'/'+jsonString2+'/'+jsonString3;
response.send(result);
}
});
}
});
}
});
}
Thanks in Advance
How about sending response along when you call the function?
var result=maildata.getMailData(input); // something missing here
Your getMailData function expects two arguments:
exports.getMailData=function(data,response) { ... }
but you give it only one:
var result=maildata.getMailData(input);
Which makes the value of the response argument undefined.
Here is what you should do:
app.post('/mailboxpost',function(request, response) {
var input=request.query.search;
maildata.getMailData(input, response);
});
and let maildata.getMailData handle the response sending, as you did in response.send(result);
I have used asynchronous callback method in my app.js.
I got the result
var result=maildata.getMailData(input,response,function(data){
response.send(data);
response.end();
});
Thanks all

Categories