Not able to insert data into sqlserver, nodejs - javascript

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.

Related

get a callback from a seperate file in node js

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")
}
};

How to call mongodb collection getall by node.js?

I wanna take the whole list of notifies from mongo db but it returns empty([]) array also I know that i need callback or shorter way of it . Do you have any idea for collecting any data from mongodb by node.js? If I call this /Notifies method (http://127.0.0.1:5000/Notifies)
var MongoClient = require('mongodb').MongoClient;
var express = require("express");
var app = express();
format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
});
return res.json(arr);
});
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function () {
console.log("Listening on " + port);
})
Don't use for docs.each instead of this use .toArray so it will return directly a array and then use Json.stringify to convert it into json string array
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
coll.find({}).toArray(function (err, result) {
if (err) {
res.send(err);
} else {
res.send(JSON.stringify(result));
}
})
});
The problem is you are returning the empty array from within the function, before the actual DB operation occurs. You need to move the line return res.json(arr);
into the find function:
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
console.log(docs);
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
return res.json(arr);
});
});
});
Also, for future use, do not reuse variable names in nested functions (you have 3 functions that use the variable err).

node js server: issue passing a variable to a function

I am building my first node.js server to perform a mysql query and return results from the database. Everything works but now I cannot find the right way to pass a value from the url (query section) to the function that performs the query (the PollingLoop function). No problems to retrieve the url and to get the parameter in the handler function but to move it to pollingLoop I have tried almost all I know about javascript (not enough I see). This is my code now that fails to run because of the reference error in pollingLoop for hwkey that is not defined.
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
url = require('url'),
fs = require('fs'),
mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'flipper',
database: 'oclock',
port: 3306
}),
POLLING_INTERVAL = 3000,
pollingTimer;
// If there is an error connecting to the database
connection.connect(function(err) {
// connected! (unless `err` is set)
if (err) {
console.log(err);
}
});
// creating the server ( localhost:8000 )
app.listen(8000);
function handler(req, res) {
console.log("INCOMING REQUEST: "+req.method+" "+req.url);
req.parsed_url = url.parse(req.url, true);
var getp = req.parsed_url.query;
var hwkey = getp.hk;
console.log(hwkey);
fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(200);
res.end(data);
});
}
function pollingLoop(){
// Doing the database query
var query = connection.query('SELECT max(id), testo, created_by FROM flashmsgs WHERE hwk="'+hwkey+'"'),
//var query = connection.query('SELECT max(id), testo, created_by FROM flashmsgs'),
flashmsgs = []; // this array will contain the result of our db query
// setting the query listeners
query
.on('error', function(err) {
// Handle error, and 'end' event will be emitted after this as well
console.log(err);
updateSockets(err);
})
.on('result', function(flashmsg) {
// it fills our array looping on each user row inside the db
flashmsgs.push(flashmsg);
})
.on('end', function() {
// loop on itself only if there are sockets still connected
if (connectionsArray.length) {
pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);
updateSockets({
flashmsgs: flashmsgs
});
} else {
console.log('The server timer was stopped because there are no more socket connections on the app')
}
});
};
// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
console.log('Number of connections:' + connectionsArray.length);
// starting the loop only if at least there is one user connected
if (!connectionsArray.length) {
pollingLoop();
}
socket.on('disconnect', function() {
var socketIndex = connectionsArray.indexOf(socket);
console.log('socketID = %s got disconnected', socketIndex);
if (~socketIndex) {
connectionsArray.splice(socketIndex, 1);
}
});
console.log('A new socket is connected!');
connectionsArray.push(socket);
});
var updateSockets = function(data) {
// adding the time of the last update
data.time = new Date();
console.log('Pushing new data to the clients connected ( connections amount = %s ) - %s', connectionsArray.length , data.time);
// sending new data to all the sockets connected
connectionsArray.forEach(function(tmpSocket) {
tmpSocket.volatile.emit('notification', data);
});
};
console.log('Please use your browser to navigate to http://localhost:8000');
just bring on hwkey variable out from handler
var hwkey;
function handler(req, res) { hwkey = ... }
pollingLoop(){console.log(hwkey);}

not able to store the data to mongoDB

I am trying since 3 hours to store the data from html form to mongodb using noddejs.
while clicking on submit it shows another page which returns the data which has been submitted in json format but it is not being stored in database.
This is my app.js:
app.use(serveStatic(__dirname+"/index.html")).listen(8080);
var mongoUri = 'mongodb://localhost/test';
//Note that I am changing the dbname and trying to store data in different //db will also shows the same error
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function () {
throw new Error('unable to connect to database at ' + mongoUri);
});
console.log("connection successfull");
app.use(express.bodyParser());
app.use(express.static(__dirname + "/" ));
app.use(bodyParser.urlencoded({extended:true}));
app.post('/InquiryDetails', function(req,res){
res.json(req.body);
console.log(req.body);
});
require('./models/InquiryDetails');
app.listen(4000);
console.log('Listening on port 4000...');
this is my model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var myskyllSchema = new Schema({
name: String,
email: String,
state: String,
country: String,
school: String,
profession: String,
phone: Number
});
mongoose.model('InquiryDetails', myskyllSchema);
This is my controller:
var mongoose = require('mongoose'),
InquiryDetails = mongoose.model('InquiryDetails');
exports.add = function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
});
}
Any help will be appreciated.
Just replace the code in app.js :
app.post('/InquiryDetails', function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
res.send(req.body);
});
});
instead of :
exports.add = function(req, res) {
InquiryDetails.create(req.body, function (error, details) {
if (error) return console.log(error);
return res.send(details);
});
}
The reason is controller was unable to load and method add is not registered with post method. Now it is working.

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