How to make a insert statement in express - node.js

I have express server code below
I want to initiate an insert statement by getting the param value
Then inserting that param value into Database
What i have done so far is that i have learnt how to make JSON response ::
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '*****',
password: "*****",
database: 'DB-NAME'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 1234);
app.use(express.static(__dirname + '/public/images'));
app.get('/Name/',function(request,response,next){
var keyName=request.query.Key;
var name_of_restaurants;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM RestaurantDescription where RestaurantName = ?', [keyName], function (err, rows, fields)
{
console.log('Connection result error ' + err);
name_of_restaurants = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants
});
} );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
What i am trying to do::
I am trying to find how to make a insert statement
So that i could extract the Param value and insert that data to
database
How to modify the above code to achieve my goal
Hope i am clear !
[EDIT]
var express = require('express')
, async = require('async')
, http = require('http')
, mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: '*********',
password: "*********",
database: 'DB_NAME'
});
connection.connect();
// all environments
app.set('port', process.env.PORT || 7000);
app.use(express.static(__dirname + '/public/images'));
app.get('/Name/',function(request,response,next){
var keyName=request.query.Key;
var name_of_restaurants;
async.series( [
function(callback) {
connection.query('INSERT INTO RestaurantDescription (RestaurantName) VALUES (?)', [keyName], function (err, rows, fields)
{
console.log('Connection result error ' + err);
callback();
});
}
// Send the response
] );
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

I'm not familiar with the libraries which you use but I think that you should add another function inside the array passed to async.series. The body of the function should have similar content as the one above.
async.series( [
// Get the first table contents
function(callback) {
connection.query('SELECT * FROM RestaurantDescription where RestaurantName = ?',
[keyName],
function (err, rows, fields) {
console.log('Connection result error ' + err);
name_of_restaurants = rows;
callback();
}
);
},
// inserting a value
function(callback) {
connection.query('INSERT INTO RestaurantDescription (RestaurantName) VALUES (?)',
[keyName],
function (err, rows, fields) {
console.log('Connection result error ' + err);
callback();
}
);
}
]
What will happen is that the both function will be executed asynchronous and at the end you will still send a response to the browser.
You are already getting a GET parameter via var keyName=request.query.Key;.
If you plan to use POST parameters, instead of
var keyName=request.query.Key;
You should add a middleware which parses the variables:
app.use(express.bodyParser());
And then
var keyName = request.body.Key;
I'm referring this comment https://stackoverflow.com/a/18167056/642670

Related

Node JS to SQL SERVER get null empty when i trying conect

var app = require('express')();
app.get('/', (req, res) => {
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'xxxxx',
server: 'xx',
database: 'formdangky',
port :'1443'
};
(async function () {
try {
let pool = sql.connect(config)
let result1 = await pool.request()
.query('select * from dondangky')
// console.dir(result1)
// send records as a response
res.send(result1);
} catch (err) {
res.send(err)
}
})();
sql.on('error', err => {
// error handler
console.log(err);
});
});
//start listening
var port = 3000;
app.listen(port, function () {
console.log('Application started on ' + new Date());
console.log("Listening on " + port);
});
When i trying code but then the result is empty end not show something
Node JS to SQL SERVER get null empty when i trying conect with mssql from Npm https://www.npmjs.com/package/mssql#asyncawait
to get reslut from database

NODE.js Insert into SQL Server

I am trying to perform an INSERT into my SQL Server through my NODE.js server
but it is not working.
I believe it is not a connection problem because (as I will demonstrate at the end of the post) I did a select that worked, so I must be making some mistake in the node.js code.
This is the first javascript system I create.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', function (req, res) {
var body = req.body;
var sql = require("mssql");
console.log("C1");
sql.connect('mssql://login:pswd#serv/db', function (err) {
if (err) console.log(err);
// create Request object
console.log("Connected!");
var insert = "INSERT into dbo.WIDS_API_TEST (Programm, ID, Titlw) VALUES ('Teste 1 2 3 ', '39', 'Finance')"
// query to the database and get the records
sql.query(insert, function (err, result) {
if (err) console.log(err)
// send records as a response
console.log("1 record inserted");
});
});
});
//var server = app.listen(5000, function () {
// console.log('Server is running..');
//});
What am I doing wrong? Because the INSERT did not even show my console.logs =/
When I performed a test doing a select it worked, so
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
/* var config = {
user: 'papercut',
password: 'Portage.2018',
server: 'devsqlcl2:1433',
database: 'AgrM6',
port: "1433",
dialect:",ssql",
dialectOptiond:"SQLEXPRESS"
};*/
// connect to your database
sql.connect('mssql://login:pswd#server:1433/database', 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 dbo.balance_papercut', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
This SELECT statement worked.

Cannot GET /api/addmasterlist on app.post

server.js
var express = require('express');
var mysql = require('mysql');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require("method-override");
var request = require("request");
app.use(express.static(__dirname + '/public'));
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({'extended' : 'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json'}));
app.use(methodOverride());
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
port : 3306,
user : 'root',
password : 'xxxxxxx',
database : 'masterlist',
debug : false
});
//Rest APIs
app.get('/api/fetchmasterlist', function(req, res){
pool.getConnection(function(err, connection){
if(!err){
//Query
var strquery = "SELECT * FROM students";
connection.query(strquery, function(err, rows){
if(err){
res.json("Error in Query." + err);
}else{
res.json(rows);
}
});
}else {
//Return an Error
connection.release();
connection.destroy();
res.json("Error geting connection from DATABASE.");
return;
}
});
});
app.post('/api/addmasterlist', function(req, res){
pool.getConnection(function(err, connection){
if(!err){
//Query
/*var post = req.body.param;*/
var strquery = "INSERT INTO students(id, studentid, studentname, course, year) VALUES (?, ?, ?, ?, ?)";
connection.query(strquery, [req.body.id, req.body.studentid, req.body.studentname, req.body.course, req.body.year], function(err, rows){
if(err){
res.json("Error in Query." + err);
}else{
res.json("Success in inserting the new student." + rows);
}
});
}else {
//Return an Error
/*connection.release();
connection.destroy();*/
res.json("Error geting connection from DATABASE.");
return;
}
});
});
// application route
app.get('*', function(req, res){
res.sendfile('./public/index.html') // load the single static file
});
// listen
app.listen(8080);
console.log("App listening on port 8080");
my api/addmasterlist is not working and it gives me
Cannot GET /api/addmasterlist
error on the browser
using app.get on the masterlist seems to work fine and reflect on the database the problem is it will not work on my angular.js
okay using app.get seems to work but can anyone help me is this the proper way of pushing through nodejs? using angular
$scope.saveNewStudent = function(){
var dataa = $scope.studentmasterlist.push({
id: ($scope.studentmasterlist.length + 1),
studentid: $scope.studentid,
studentname: $scope.studentname,
course: $scope.course,
year: $scope.year,
});
$http.get('/api/addmasterlist', dataa).success(function(data, status) {
console.log('Data posted successfully');
})
//Clear the scope
$scope.studentid = "";
$scope.studentname = "";
$scope.course = "";
$scope.year = "";
}
The problem is that you declared your /api/addmasterlist endpoint as a POST request. Try changing it to GET and it might work as you expected.
Change this:
app.post('/api/addmasterlist', function(req, res){
To this:
app.get('/api/addmasterlist', function(req, res){
Alternatively, you can change your angular's http from get to post:
Change:
$http.get('/api/addmasterlist', dataa).success(function(data, status) {
to
$http.post('/api/addmasterlist', dataa).success(function(data, status) {

connecting to PostgreSQL from NodeJS not working

I've start using NodeJS about a month ago. Since i don't have that much experience running code doesn't always go as want to. In some way i'm not able to connect to my PostgreSQL with node's pg package. (Good to know it works when i connect through PDO in PHP)
I have made this (simple) route/controller
var pg = require('pg');
var config = require('../config');
module.exports = function(app) {
app.get('/db-get-formules', function(req, res) {
var results = [];
var pgClient = new pg.Client(config.getDbConnectionString());
pgClient.connect();
pgClient.query('SELECT * FROM formules ORDER BY formule_id');
pgClient.on('row', function(row) {
results.push(row);
})
pgClient.on('end', function() {
done();
console.log(results);
res.json(results);
})
});
};
this is my index.js file in the config:
var configValues = require('./config');
module.exports = {
getDbConnectionString: function() {
return 'postgres://' + configValues.uname + ':' + configValues.password + '#' + configValues.host + ':' + configValues.port + '/' + configValues.database;
}
}
In that same config folder i have a config.json file that contains all of the parameters to connect
{
"uname": "username",
"database": "myDb",
"host": "localhost",
"password": "P#ssw0rd",
"port": "5432",
"idleTimeoutMillis": "30000"
}
If i run this /db-get-formules page the page keeps loading (spinning) and nothing really happens. What am i doing wrong?
Oh and just to provide you with my complete code, i have a server.js file in the root
var express = require('express');
var app = express();
var queryFormules = require('./controllers/queryFormules');
var port = process.env.PORT || 3000;
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/server', express.static(__dirname + '/public/server'));
queryFormules(app);
// application -------------------------------------------------------------
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
app.listen(port);
I don't see any other answers, and i'm not sure if this will help, but here is how I got it to work:
config.js
var pg = require('pg');
exports.conString = "pg://user:password#db_address:5432/db_name";
helper.js
var pg = require("pg");
var config = require('../config/config');
exports.runQuery= function(query, next) {
pg.connect(config.conString, function(err, client) {
if (err) {
var e = {
error: true,
message: "Unable to connect to database",
err: err,
};
return next(e);
}
client.query(query, function(err, result) {
//deal with the result
client.end();
return next(some_data_or_value);
});
});
}
Then you can call runQuery from anywhere, ofcourse you'll need to deal with the results / possible errors in the function as well.
some other file or function
var helpers = require('../services/helpers');
var query = "SELECT * FROM formules ORDER BY formule_id"
helpers.runQuery(query, function(result) {
//deal with results
});

Node + Q with expressjs - ordered promisses

I want to execute a set of functions in the order they were written and in the end to release the request to the client.
for example see the mock code bellow:
router.get('/dashboard', function(req, res, next) {
var json = {items : 0}
Q.fcall(
function(){
//first exec
json.items+=1;
}
).then(
function(){
//scond exec
json.items+=1;
}
).then(
function(){
//third exec
json.items+=1;
}
).finally(
function(){
//do this when all the other promises are don
res.json(json);
});
}
the finally function shoud be executed when all is done.
Can it be done with Q?
UPDATE
I think I mislead you, and did not give all the information, because i did not think its relevant, but it is...
I actually bringing data via mongoose, and mongoose is async asd well.
So it goes like this:
Q.fcall(
function() {
Visitor.count(dateRange, function(err, data) {
json.newVisitors = data;
});
}).then(
function() {
Account.count(dateRange, function(err, data) {
json.newAccounts = data;
});
}).finally(
function() {
res.json(json);
})
Mongoose is already promisified. Calling exec() on a query gives you a promise. Here are two ways of doing it:
Classic promises chaining:
Visitor.count(dateRange).exec().then(function (data) {
json.newVisitors = data;
return Account.count(dateRange).exec(); // return promise for chaining
}).then(function (data) {
json.newAccounts = data;
}).then(function () {
res.json(json);
}).catch(function (err) {
// handle errors
});
Or Promise.all:
Promise.all([
Visitor.count(dateRange).exec(),
Account.count(dateRange).exec()
]).then(function(result){
// result is an ordered array of all the promises result
json.newVisitors = result[0];
json.newAccounts = result[1];
}).catch(function (err) {
// handle errors
});
Yes:
var path = require('path'),
express = require('express'),
app = express(),
router = express.Router(),
Q = require('q');
router.get('/dashboard', function(req, res) {
var json = {items:''};
Q.fcall(function() {
json.items += 'A';
})
.then(function() {
json.items += 'B';
})
.then(function() {
json.items += 'C';
})
.finally(function() {
res.json(json);
});
});
app.use('/', router);
var http = require('http');
var port = process.env.PORT || '3000';
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('listening', function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('Listening on ' + bind);
}
);
Then
curl localhost:3000/dashboard
Returns:
{"items":"ABC"}
P.S. You might also want to investigate async-q et. al.:
async.series([
->
### do some stuff ###
Q 'one'
->
### do some more stuff ... ###
Q 'two'
]).then (results) ->
### results is now equal to ['one', 'two'] ###
doStuff()
.done()
### an example using an object instead of an array ###
async.series({
one: -> Q.delay(200).thenResolve(1)
two: -> Q.delay(100).thenResolve(2)
}).then (results) ->
### results is now equal to: {one: 1, two: 2} ###
doStuff()
.done()
UPDATED (a bit forced, I would just use async):
var path = require('path'),
express = require('express'),
app = express(),
logger = require('morgan'),
router = express.Router(),
Q = require('q'),
async = require('async-q');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
router.get('/dashboard', function(req, res) {
var json = {};
async.series({
newVisitors: function() {
return Q.Promise(function(resolve,reject) {
console.log(arguments);
Visitor.count(dateRange, function(err, data) {
if(err) return reject(err);
resolve(data);
});
});
},
newAccounts: function() {
return Q.Promise(function(resolve,reject) {
Account.count(dateRange, function(err, data) {
if(err) return reject(err);
resolve(data);
});
});
}
})
.then(function(json) {
res.json(json);
});
});
app.use('/', router);
var http = require('http');
var port = process.env.PORT || '3000';
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('listening', function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('Listening on ' + bind);
}
);
Now returns:
{"newVisitors": 1,"newAccounts":2}

Resources