I am using Node JS with IIS (IISNode) and Microsoft's MS SQL driver package (MSNodeSQL) to create a http server. When accessing my database via the http server I get the following error when attempting to connect to the MS SQL database:
error { [Error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified] sqlstate: 'IM002', code: 0 }
But if I try to access the database locally on my server without the http server, then it connects perfectly fine. The ODBC driver is obviously installed.
Here is my code:
var http = require('http');
var sql = require('msnodesql');
var conn_str = "Driver={SQL Server Native Client 11.0}; Server=***; Database=***; UID=***; PWD=***;";
var blah = "";
http.createServer(function (req, res) {
sql.open(conn_str, function (err, conn) {
if (err) {
console.log("error", err);
res.end("error");
return;
}
conn.queryRaw("SELECT * FROM ProductLinks", function (err, results) {
if (err) {
res.end('failed2');
return;
}
for (var i = 0; i < results.rows.length; i++) {
blah += "Id: " + results.rows[i][0] + " Name: " + results.rows[i][1] + " Text: " + results.rows[i][2] + " Link: " + results.rows[i][3];
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(blah);
});
});
}).listen(process.env.PORT);
I have a feeling it may be down to permissions somewhere since it works locally and not remotely, but I'm not entirely sure. Plus when locally, Node JS is being executed under a different user as opposed to IIS_IUSR which IISNode uses.
Any help would be great, thanks!
I tried Node-MSSQL it's very good and very simple to use and it's connected and gets data successfully but it works on sql authentication only
Related
I am trying to capture client ipaddress for traffic visiting my localhost:8080. I am using the following modules and the node.js application looks like this
var connect = require('connect');
var http = require('http');
var net = require('net');
var express = require('express');
var app = express();
var app = connect();
// require request-ip and register it as middleware
var requestIp = require('request-ip');
// you can override which attirbute the ip will be set on by
// passing in an options object with an attributeName
app.use(requestIp.mw({ attributeName : 'myCustomAttributeName' }))
// respond to all requests
app.use(function(req, res) {
// use our custom attributeName that we registered in the middleware
var ip = req.myCustomAttributeName;
console.log(ip);
fs.appendFile('iplist.csv', ip, 'utf8', function (err) {
if (err) {
console.log('Some error occured - file either not saved or corrupted file saved');
} else{
console.log('It\'s saved!');
}
});
// https://nodejs.org/api/net.html#net_net_isip_input
// var ipType = net.isIP(ip); // returns 0 for invalid, 4 for IPv4, and 6 for IPv6
// res.end('IP address is ' + ip + ' and is of type IPv' + ipType + '\n');
});
//create node.js http server and listen on port
app.listen(8080);
Is there any way I can listen to the already existing server without creating my own, hence avoiding the conflict of two servers fighting for the same port. I am new to node.js. Any help will be great. Thank you!
I have opened the server.js and the address:http://localhost:8081 on my browser. But then a text "Upgrade Required" appeared at the top left conern of the website.
What is the problem of that? What else do I need to upgrade?
Here is the server.js:
var serialport = require('serialport');
var WebSocketServer = require('ws').Server;
var SERVER_PORT = 8081;
var wss = new WebSocketServer({
port: SERVER_PORT
});
var connections = new Array;
SerialPort = serialport.SerialPort,
portName = process.argv[2],
serialOptions = {
baudRate: 9600,
parser: serialport.parsers.readline('\n')
};
if (typeof portName === "undefined") {
console.log("You need to specify the serial port when you launch this script, like so:\n");
console.log(" node wsServer.js <portname>");
console.log("\n Fill in the name of your serial port in place of <portname> \n");
process.exit(1);
}
var myPort = new SerialPort(portName, serialOptions);
myPort.on('open', showPortOpen);
myPort.on('data', sendSerialData);
myPort.on('close', showPortClose);
myPort.on('error', showError);
function showPortOpen() {
console.log('port open. Data rate: ' + myPort.options.baudRate);
}
function sendSerialData(data) {
if (connections.length > 0) {
broadcast(data);
}
}
function showPortClose() {
console.log('port closed.');
}
function showError(error) {
console.log('Serial port error: ' + error);
}
function sendToSerial(data) {
console.log("sending to serial: " + data);
myPort.write(data);
}
wss.on('connection', handleConnection);
function handleConnection(client) {
console.log("New Connection");
connections.push(client);
client.on('message', sendToSerial);
client.on('close', function () {
console.log("connection closed");
var position = connections.indexOf(client);
connections.splice(position, 1);
});
}
function broadcast(data) {
for (c in connections) {
connections[c].send(data);
}
}
OK, websockets...
The "upgrade required" status marks the start of a websocket handshake. Normally your client sends this first to the WS server. The server answers in a pretty similar manner (details here : https://www.rfc-editor.org/rfc/rfc6455 ), and then proceed to pipe the actual data.
Here, you're opening a connection from your client as regular http, sending a simple GET. What you see on the screen is the server dumbly proceeding with an already corrupted handshake.
That's not how you open a WS client side connection. You don't usually open WS pages from the browser. It ought to be opened from a JavaScript call, such as new WebSocket(uri). So what you want is a regular http server on another port, that serves a page containing the necessary Javascript to open the actual WS connection and do something useful with its data. You'll find a clean example here : http://www.websocket.org/echo.html
I'm trying to send data between an Android application created with Cordova and an application running on a Windows machine; the application on the Windows machine requires TCP protocol. I've worked with Cordova before, but I haven't used many plugins for Cordova--and therefore I've had difficulty setting up plugins--and socket programming isn't familiar ground for me.
Anywho, I read that I could use chrome.socket with Cordova somewhere, so I've tried doing that, but I'm only receiving errors indicating that "chrome" is undefined.
I first installed the plugin via command line: cordova plugin add org.chromium.socket
It then appeared in the plugins directory of my Cordova application.
Then, I included the following code in my application:
var dataString = "Message to send";
var data = new Uint8Array(dataString.length);
for (var i = 0; i < data.length; i++) {
data[i] = dataString.charCodeAt(i);
}
try {
chrome.socket.create("tcp", function(createInfo) {
var socketId = createInfo.socketId;
try {
chrome.socket.connect(socketId, hostname, port, function(result) {
if (result === 0) {
chrome.socket.write(socketId, data, function(writeInfo) {
chrome.socket.read(socketId, 1000, function(readInfo) {
});
});
}
else
{
alert("CONNECT FAILED");
}
});
}
catch (err)
{
alert("ERROR! " + err);
}
});
}
catch (err)
{
alert("ERROR! " + err);
}
I get the error alert every time, because chrome.socket is undefined; this makes me think that I did not set this up correctly. At any rate, any advice would be greatly appreciated.
I am in a trouble while coding ssh2 module in my project. I tried to run multiple commands on one terminal for ruling remote Linux system. For example "bc" command provides you a basic calculator and you can run it for basic operations. but that kind of processes need to be awake when you are using (it will accepts two or more input and it will give a response as a result).
I need to create a system like work with websocket and ssh. When a websocket received a command ,ssh node need to execute this message and Module need to send it's response via websocket.send()
I am using Node.js websocket,ssh2 client.
Here my code :
#!/usr/bin/node
var Connection = require('ssh2');
var conn = new Connection();
var command="";
var http = require('http');
var WebSocketServer = require('websocket').server;
var firstcom=true;
conn.on('ready', function() {
console.log('Connection :: ready');
// conn.shell(onShell);
});
var onShell = function(err, stream) {
// stream.write(command+'\n');
stream.on('data', function(data) {
console.log('STDOUT: ' + data);
});
stream.stderr.on('data', function(data) {
console.log('STDERR: ' + data);
});
}
var webSocketsServerPort=5000;
var ssh2ConnectionControl=false;
var server = http.createServer(function (req, res) {
//blahbalh
}).listen(webSocketsServerPort, function() {
console.log((new Date()) + " Server is listening on port:: " + webSocketsServerPort);
});
//console.log((new Date()) + 'server created');
wsServer = new WebSocketServer({
httpServer: server,
// autoAcceptConnections: false
});
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
var wsconnection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
if(!ssh2ConnectionControl){
conn.connect({
host: 'localhost',
port: 22,
username: 'attilaakinci',
password: '1'
});
ssh2ConnectionControl=true;
console.log('SSH Connected.');
}
wsconnection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
command=message.utf8Data;
//if(firstcom){
// conn.shell(onShell);
// firstcom=false;
//}else{
conn.exec(message.utf8Data,onShell);
//}
wsconnection.send(message.utf8Data);
}
else{
console.log('Invalid message');
}
});
wsconnection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + wsconnection.remoteAddress + ' disconnected.');
});
});
You should use conn.shell() instead of conn.exec() if you want a real interactive shell. conn.exec() is typically for executing one-liner commands, so it does not persist "shell state" between conn.exec() calls (e.g. working directory, etc.).
You should also be aware of possible limits by your SSH server has set up as far as how many simultaneous shell/exec requests are allowed per connection. I think the default limit for this on OpenSSH's server is 10.
This is an old question but I wanted to provide a alternative method usings sh2shell which wraps ssh2.shell by mscdex, used above. The example below only covers making the ssh connection, running the commands and processing the result.
Using ssh2shel it is possible to run any number of commands sequentually in the context of the previous commands in the same shell session and then return the output for each command (onCommandComplete event) and/or return all session text on disconnection using a callback function.
See the ssh2shell readme for examples and lots of info. There are also tested scripts for working code examples.
var host = {
//ssh2.client.connect options
server: {
host: 120.0.0.1,
port: 22,
userName: username,
password: password
},
debug: false,
//array of commands run in the same session
commands: [
"echo $(pwd)",
command1,
command2,
command3
],
//process each command response
onCommandComplete: function( command, response, sshObj) {
//handle just one command or do it for all of the each time
if (command === "echo $(pwd)"){
this.emit("msg", response);
}
}
};
//host object can be defined earlier and host.commands = [....] set repeatedly later with each reconnection.
var SSH2Shell = require ('ssh2shell');
var SSH = new SSH2Shell(host),
callback = function( sessionText ){
console.log ( "-----Callback session text:\n" + sessionText);
console.log ( "-----Callback end" );
}
SSH.connect(callback)
To see what is happening at process level set debug to true.
I'm trying to connect to a remote database from my phonegap app.
I'm using an example script I found, but it's not working, as I keep getting require is not defined error.
Here's my code (it's inside a tag):
var Client = require('mysql').Client;
var client = new Client();
client.host ='1**.**.**.**8:****';
client.user = '*****';
client.password = '*****************';
console.log("connecting...");
client.connect(function(err, results) {
if (err) {
console.log("ERROR: " + err.message);
throw err;
}
console.log("connected.");
clientConnected(client);
});
clientConnected = function(client)
{
tableHasData(client);
}
tableHasData = function(client)
{
client.query(
'SELECT * FROM test_db.Users LIMIT 0,10',
// you can keep this function anonymous
function (err, results, fields) {
if (err) {
console.log("ERROR: " + err.message);
throw err;
}
console.log("Got "+results.length+" Rows:");
for(var i in results){
console.log(results[i]);
console.log('\n');
//console.log("The meta data about the columns:");
//console.log(fields);
}
client.end();
});
};
What am I doing wrong??
You are probably using nodeJS code that can't be run on Cordova. This must be run with node.
What you need to do is create a server (where you will run your code with nodeJS) and expose your data through an API for the client (your Cordova app) to come and fetch them. (Use AJAX requests)