Unable to connect with SQL Server using Node.js - javascript

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.

Related

Code after stored procedure query not being executed in nodejs msnodesqlv8

I'm trying to execute a stored procedure and when I run the code below, the code in the function for the query is not being run at all. There is also no error. I am thinking somehow SQL Server is interpreting the query for the stored procedure incorrectly and stalling because if I use a regular query e.g. select top 1 * from Custom.ExampleTable it works fine.
var express = require('express');
var app = express();
const sql = require("mssql/msnodesqlv8");
// example db connection...
const connectionString = "server=dev\\instance1;database=123456;user=ORG\\NAME;Trusted_Connection=Yes;"
sql.connect(connectionString, err => {
console.log("connected: " + connectionString)
try {
new sql.Request().input('var', sql.VarChar, 2222).execute('dbo.check_ex', (err, results) => {
// code not being run...
console.dir("test")
if (err) {
console.log(err);
}
console.log(rows);
})
} catch (err) {
console.log(err);
}
})
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Output below:
Server is running..
connected: server=dev\\instance1;database=123456;user=ORG\\NAME;Trusted_Connection=Yes;

Node js works fine but how do I get it on browser?

I have a table in sql Server and I am trying to display it in web browser and apply datatable(jQuery) to it. Below code works fine as it gives the output in command line. But I'd have to get it on the browser(probably in json format).
I am using 'tedious' for connection as that's what I found in Express.js documentation.
var express = require('express');
var app = express();
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var config = {
userName: 'clientinfo',
password: 'clientinfo123',
server: 'USW20051234'
}
var connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
console.log(err);
} else {
executeStatement();
}
});
function executeStatement() {
request = new Request("SELECT * from dbo.Logs", function (err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount+' rows');
}
connection.close();
});
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(JSON.stringify(column.value));
}
});
});
connection.execSql(request);
}
You need to start HTTP server. As you already define APP try this
app.get('/urltest', (req, res) => {
res.send('hello from nodejs');
});
const PORT = 5000;
app.listen(PORT);
console.log('Listening on :' + PORT + '...');
and try http:localhost:5000/urltest on a browser
Thank You everyone for all the suggestions. I think "tedious" was giving me a hard time so I did npm install mssql and that worked like a charm.
Below is the link I referred to.
http://www.tutorialsteacher.com/nodejs/access-sql-server-in-nodejs

Can't Get The Php Variable To My Node Js using npm: exec-php module

Following is the Server.js File, here I am Fetching The Details From Table which working Good. I need to Get a Variable From k.php which is in the Same Folder.Iam using npm exec-php module to get the Values From Php File. But The Variable is Showing Undefined.
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
express=require('express'),
session=require('express-session'),
mysql = require('mysql'),
execPhp = require('exec-php'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'test',
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.php', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.php');
}
res.writeHead(200);
res.end(data);
});
}
execPhp('k.php', function(error, php, outprint){
// Here I expected The outprint Will be 'One' but it print undefined
console.log(outprint);
php.my_function(1, 2, function(err, result, output, printed){
//this my_function is also showing Error
});
});
var pollingLoop = function() {
// Doing the database query
var query = connection.query('SELECT * FROM users where user_id=1'),
users = []; // 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(user) {
// it fills our array looping on each user row inside the db
users.push(user);
})
.on('end', function() {
// loop on itself only if there are sockets still connected
if (connectionsArray.length) {
pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);
updateSockets({
users: users
});
} 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');
the main Problem is in these Lines
execPhp('k.php', function(error, php, outprint){
// Here I expected The outprint Will be 'One' but it print undefined
console.log(outprint);
php.my_function(1, 2, function(err, result, output, printed){
//this my_function is also showing Error
});
});
The Following is k.php in the same folder
<?php
echo "One";
function my_function($arg1, $arg2){
echo "Two";
return $arg1 + $arg2;
}
?>
This is the Error

trying to fetch specific data from mysql using node.js

i am new to node.js and my boss has entrusted me with a job to integrate a notification system in our attendance project..
so far i have successfully created a connection to my data base using express and mysql node modules
and the code that helped me in achieving that is given below
var express=require('express');
var mysql=require('mysql');
var app=express();
var connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'attendance'
});
connection.connect(function(error) {
if(!!error) {
console.log('Error in connection');
} else {
console.log('Connected');
}
});
app.get('/',function (req, resp) {
connection.query("Select * from employee_leaves", function (error, rows, fields) {
if (!!error) {
console.log("Error in the query");
} else {
console.log("successfully done\n");
console.log(rows);
}
});
})
app.listen(1337);
// now the issue is i want to query this statement
SELECT * from employee_leaves WHERE employee_leave_company_name ='$sup_company_name' AND leave_status='Pending'ORDER BY employee_leave_id desc"
the issue is these variable $sup_company_name is in php so
1) how should i fetch value from that variable
2)how to use where clause in node.js
Note:: $sup_company_name is declared in my require.php file
the code of require.php file is given below P.S i m accessing that variable in my other pages by include('require.php') but i dont know how to access that variable in node.js
session_start();
$sup_id = $_SESSION['employee_id'];
$sup_type=$_SESSION['employee_type'];
$sup_company_name=$_SESSION['employee_company_name'];

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

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

Categories

Resources