Connecting to MS SQL DB with node.js + functions() - javascript

I am trying to connect to a MS SQL Server DB using node.js. I installed the msnodesql module to use for this task. I am able to connect to a DB with the following code:
var sql = require('msnodesql');
var util = require('util');
//
var connStr = "Driver={SQL Server Native Client 11.0};Server=myySqlDb,1433;Database=DB;UID=Henry;PWD=cat;";
var query = "SELECT * FROM GAData WHERE TestID = 17";
sql.open(connStr, function(err,conn){
if(err){
return console.error("Could not connect to sql: ", err);
}
conn.query(query,function(err,results){
if (err){
return console.error("Error running query: ", err);
}
console.log(results);
console.log(results.length);
for (var i = 0; i <= results.length; i++){
util.inspect(results[i]);
}
});
});
My goal however is to connect to the DB from various events, such as button submits, from a HTML page. From the button click I want to call a node.js function to query the DB for a particular attribute, such as the following:
From the HTML:
<br /><button type="submit" id="continue" onClick="verifyEmail($('#email').val())">Continue</button>
From the script file:
function verifyEmail(email){
var mQuery = "'EXEC WebUserRecovery '" + email + "'";
sql.open(conn_str, function (err, conn) {
if (err) {
console.log("Error opening the connection!\r\n" + err);
return;
}
connection.query(mQuery,function(err,results){
if (err){
return console.error("Error running query: ", err);
}
alert(results);
});
});
}
The code when put inside the function does not work, a DB connection is unsuccessful. Can anyone advise how to fix this issue? There is little good documentation on msnodesql out there...

Server side .js file (Node.js):
var sql = require('msnodesql');
var util = require('util');
var connStr = "Driver={SQL Server Native Client 11.0};Server=myySqlDb,1433;Database=DB;UID=Henry;PWD=cat;";
var query = "SELECT * FROM GAData WHERE TestID = 17";
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
sql.open(connStr, function(err,conn){
if(err){
return console.error("Could not connect to sql: ", err);
}
conn.query(query,function(err,results){
if (err){
return console.error("Error running query: ", err);
}
response.writeHead(200, {"Content-Length": results.length});
response.writeHead(200, {"Content-Type": "application/json"});
response.end(results);
});
});
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
At Client Side .js file or in-line script should be something like following using jQuery ajax call:
var request = $.ajax({
url: "http://127.0.0.1:8000/",
type: "GET",
dataType: "json"
});
request.done(function(dataRcvd) {
alert(JSON.stringify(dataRcvd));
});

Related

Getting a 404/405 error while making a post request from front end AJAX to a given route in node Js. The localhost URL doesn't work

I want to load data from database as soon as page loads at front end, therefore I specified the route as '/' in GET. I am able to get the records in the console but my page doesn't load at http://127.0.0.1:3000. Here is a snap of the way I am creating server through node:
Yes I actually ran my server side through node app.js before creating this server
Moreover, even if it opens, and when I try to make a POST request to '/details' route, I get http 405 error. Here is a snap of my index.html where I am making an AJAX request:
In other ways, if I specify route as '/' in node Js and then make a request to '/', it inserts the record the way I want to.
I am quite new to AJAX and node Js. Can someone tell me where am I going wrong?
Here is my entire server side code:
const fetchOptions = {
headers: {
'Content-Type': 'application/json'
},
mode: 'cors'
};
var http=require("http");
var mysql=require("mysql");
var express=require('express');
var fs=require('fs');
var bodyParser=require('body-parser');
var app=express();
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
console.log('Creating the http server');
var con= mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "budget_mgmt"
});
con.connect(function(err){
if(err)
{
console.log('Error connecting to db');
return;
}
console.log('Connection established');
});
var statement= "select * FROM budget_mgmt.item_description";
app.get('/',function(request,response)
{
fs.readFile('index.html',function(err,data)
{
console.log("The home page: index.html");
});
con.query(statement,function(error,results, fields)
{
if(error) throw error;
console.log(results);
response.end(JSON.stringify(results));
}); //response.end(data);
});
app.post('/details',function(request,response)
{
console.log(request.body);
console.log(request.body.description);
console.log(request.body.category);
console.log(request.body.amount);
console.log(request.body.date);
var sql = "INSERT INTO item_description(description,category,amount,today) VALUES ('"
+request.body.description+"','"+request.body.category+"',"+request.body.amount+","+"date_format(str_to_date('"+request.body.date+
"','%m-%d-%Y'),'%Y-%m-%d'));";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
http.createServer(app).listen(3000,"127.0.0.1");

Unable to connect with SQL Server using Node.js

I have created an application using Node.js to connect with SQL Server. Below is the code:
app.get('/SalesStatistics', function (req, res) {
var Connection = require('tedious').Connection;
// config for your database
var config = {
user: "****",
password: "*****",
server: "abc",
database: "xyz"
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("select * from employee;", function (err) {
if (err) {
console.log(err);
}
});
var result = "";
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
result += column.value + " ";
}
});
console.log(result);
result = "";
});
request.on('done', function (rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
});
Received the below error in console:
message: 'Requests can only be made in the LoggedIn state, not the Connecting state'
code: EIINVALIDSTATE
Also tried the sample from Github site, but still I could not connect to SQL Server. Please let me know if any other possibility.
I just encountered the same problem awhile ago running the same code above with similar environment.
It turn out that I did not configure the sql server (using Sql Server Management Manager) to accept TCP connection to port (1433). After I done that, everything work fine.

How can i pipe mysql data to a browser window instead of the console in Nodejs?

Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});

cross domain error with node.js server

I am a newbie with node.js and I am trying to set up my first installation. I have a server.js where I define a new server:
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'flipper',
database: 'oclock',
//database: 'nodejs',
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);
// on server started we can load our client.html page
function handler(req, res) {
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);
});
}
Next I create a client.html file that should connect to the server and retrieve the data:
<div id="container">Loading ...</div>
<script src="node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// create a new websocket
var socket = io.connect('http://oclock.dyndns.org:8000');
// on message received we print all the data inside the #container div
socket.on('notification', function (data) {
var usersList = "<dl>";
$.each(data.users,function(index,user){
usersList += "<dt>" + user.user_name + "</dt>\n" +
"<dd>" + user.user_description + "\n" +
"<figure> <img class='img-polaroid' width='50px' src='" + user.user_img + "' /></figure>"
"</dd>";
});
usersList += "</dl>";
$('#container').html(usersList);
$('time').html('Last Update:' + data.time);
});
</script>
When I try to connect to the server using client.html using the url http://oclock.dyndns.org/client.html I see that the request is blocked for a cross origin request. The request url is http://oclock.dyndns.org:8000/socket.io/?EIO=3&transport=polling&t=1428917662987-0.
What am I missing? What am I doing wrong?
Origins are based on:
Scheme (http in both cases)
Hostname (oclock.dyndns.org in both cases)
Port Number (80 on one, 8000 on the other)
So you do have different origins. Set up CORS as usual.

Why I couldn't get first few responses from nodeJS' httpServer?

I'm planning to use nodeJS as my comet server and I wrote some code for testing, but there is an issue that when client connected to the server for the first time, it couldn't get response from server.
Here is the server-side code (server.js):
var util = require('util');
var redis = require('redis').createClient(6379, '192.168.1.254');
var http = require('http');
redis.on("error", function (err) {
console.log("Error " + err);
});
var server = http.createServer(requestListener);
server.listen(9898, '192.168.1.254');
function requestListener(req, res) {
util.log('Connected.');
redis.brpoplpush('msg:q:1', 'msg:s:1', 20, function(err, reply) {
if (err) {
util.log('ERROR: ' + err);
}
var length = reply ? reply.length : 0;
res.writeHead(200, {
'Content-Type':'text/plain',
'Content-Length':length
});
if (length) {
res.end(reply);
util.log('Sent: ' + reply);
} else {
res.end('');
}
});
}
And the client code (client.sh):
#!/bin/bash
while [ 1 ]
do
curl -i http://192.168.1.254:9898
done
I tested it following steps:
node server.js
./client.sh
In redis, LPUSH('msg:q:1', 'blablah')
Now, "Sent: blablah" printed on console, res.end(reply) excuted, but client receives nothing. I repeat step 3 for many times, then it works as expect. If I restart the client, the first few responses can't be received again.
How can I resolve this?
I think what might happening here is you've aborted curl while it was waiting for the response from redis. After the HTTP client is aborted, the redis command still stays active. You then push another element onto the queue, the redis command returns, but has no HTTP response to write it to. When you start the curl loop again, you find the queue empty.
Here's a modified version of your program that streams the response and detects a client abort. It doesn't put the element back on the queue, but you could certainly do that as well.
var util = require('util');
var redis = require('redis').createClient();
var http = require('http');
redis.on("error", function (err) {
console.log("Redis error " + err);
});
redis.on("ready", function () {
console.log("Redis client ready");
});
var server = http.createServer(requestListener);
server.listen(9898);
function requestListener(req, res) {
var aborted = false;
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.write("Checking redis...\n");
redis.brpoplpush('q', 's', 20, function (err, reply) {
if (aborted) {
return console.log("Client aborted before redis reply came back.");
}
if (err) {
return res.end("Redis error");
}
res.end("Redis reply: " + reply);
});
req.on("aborted", function () {
console.log("HTTP client aborted.");
aborted = true;
});
}

Categories

Resources