Node.Js prompt user input - javascript

I'm creating a desktop application that talks to SQL Server for MAC users using Node.JS.
Is it possible in Node.JS to take the input from the user and display the data from SQL server based on user input?
For example, in the code below, can I put an input box onload and allow user to input customercode and display InvoiceNumber and customername.
Also, will I be able to run the below code on MAC?
#Serger B,
I followed the link you suggested and was successfully able to connect to SQL Server. How can I add a user prompt to enter the customerCode for the below code? Also, it would be great is someone could help me running the script from the browser.
var sql = require('mssql');
var config = {
user: 'temp',
password: 'test123',
server: 'laptop\\localDB', // You can use 'localhost\\instance' to connect to named instance
database: 'AVTemp01',
}
var connection = new sql.Connection(config, function(err) {
// ... error checks
// Query
var request = new sql.Request(connection); // or: var request = connection.request();
request.query('select top 5 companycode from invoiceheader', function(err, recordset) {
// ... error checks
console.dir(recordset);
});
// Stored Procedure
var request = new sql.Request(connection);
request.input('input_parameter', sql.Int, 10);
request.output('output_parameter', sql.VarChar(50));
request.execute('procedure_name', function(err, recordsets, returnValue) {
// ... error checks
console.dir(recordsets);
});
});

You should try this module to access the SQL server: https://www.npmjs.org/package/mssql
We use it successfully in our projects.
The quick example on the project homepage just shows it all.
And I don't see anything preventing you to do it on Mac.

Related

Zombie.js - How to check the result of a form submission on DB?

Goal: Using Mocha, Zombie.js, and Mongoose, I am trying to test a signup form. I want to make sure that the user is added to the database using the following code:
describe('User Signup', function() {
before(function(done) { //setup db connection and browser
conn = mongoose.connect('mongodb://localhost', function(err) {
browser = new Browser({site: 'http://localhost:3000'});
done();
});
});
before(function(done) { //go to signup page
browser.visit('/user/signup', done);
});
it('can signup a new user', function(done) {
browser.fill("input[name='username']", 'johnDoe');
browser.fill("input[name='pwd']", 'password');
browser.fill("input[name='pwd_retype']", 'password');
browser.fill("input[name='city']", 'New York, NY');
browser.pressButton('#signup-submit').then(function() {
chai.assert.isOk(browser.success);
UserModel.findOne({username: 'johnDoe'}, function(er, usr) {
chai.assert.ifError(er);
chai.assert.isNotNull(usr); //check if user was added to DB
done();
});
});
});
});
Problem: The user gets added to the DB, but it gets added as a blank user (no username, password, etc). I checked the router that handles the request and put a console.log printing the username to see if zombie.js fills out the form fields, but the fields print empty. I get the following output:
So when the mocha test runs the first time, I get the line SAVE ATTEMPT FOR: with a blank username value. However, when I change a document and save, then I get the output again except with the correct value SAVE ATTEMPT FOR: johnDoe.
I don't understand why the request is sent again when I save my js files. Of course this happens way after my tests evaluate. Anyone have ideas as to what could be the problem?

Trying to connect to SQL Server 2014 on NodeJS

I am trying to connect to SQL Server 2014 with NodeJS, i am using the "mssql" package, i dont have answer here is my code
var sql = require('mssql');
var opciones = {
user: 'myuser',
password: 'mypass',
server: 'myserver',
database: 'mydatabase',
options: {
encrypt: true
}
};
sql.connect(opciones,function(err){
if(err){
console.log(err);
}else{
console.log("CONEXIÓN EXITOSA");
}
});
the name of that js is "cnSQL.js", when i execute on cmd "node cnSQL" I dont have answer.
Tested the code as above with my local DB instance.
The code is actually correct.
var sql = require('mssql');
var opciones = {
user: 'sa',
password: 'mypass',
server: '127.0.0.1',
database: 'mydb',
options: {
encrypt: true
}
};
sql.connect(opciones,function(err){
if(err){
console.log(err);
}else{
console.log("CONEXIÓN EXITOSA");
}
});
I have managed to get the 'Connexion Exitosa' message.
In order to further debug your issue, attempt the following:
With the username you are trying to login with (In my case 'sa')
Open SQL Server Management Studio and attempt to put in the connection information as above. Click login, does that work?
If not:
Open SQL Server Management Studio
Connect to the SQL Server Instance you are trying to connect to from NodeJS
Right click on the instance of your SQL server and click properties
Click security and ensure that the "SQL Server and Windows Authentication mode" radio button is selected.
When done click OK
On the left hand navigation expand the Node "Security"
Expand Logins
Find your user and ensure it is enabled and that the password you selected reflects the password within your NodeJS app.
If so:
Amend all the information within the code to reflect exactly the credentials used to login
Special Note: '.' will not represent localhost here. Use 127.0.0.1 or localhost
Furthermore, if the SQL server instance you are trying to connect to is not hosted locally. Ensure that the machine it is hosted on accepts connections on port 1433 (by default for SQL Server).
Hope it helps!

How to query postgres database for existing email

I am trying to create a very simple registration method on my project but I am having trouble figuring out how to stop postgres from adding in people with the same email. I am using postgres and Node.js.
I have an add function that I want to return false my postgres table already has a user with the email he/she tried using. I do the following:
function checkExistingEmail(email, cb){
pg.connect(cstr, function(err, client, done){
if(err){
cb(err);
}
else{
var str = 'SELECT email from Swappers where email=$3';
client.query(str, function(err, result){
if(err){
cb(err);
}
else{
console.log(result.row.email);
if(result.row.email === undefined){
cb(false);
}
else{
cb(true);
}
}
});
}
});
}
Now when I display result.row.email to the console I get that it is undefined. Which is what I want for the first time user, so it should return true, and I should be able to add the user to the database and move on. But that is not the case.
In a file I have called users.js I have the following route handler:
router.post('/authnewuser', function(req,res){
// Grab any messages being sent to use from redirect.
var authmessage = req.flash('auth') || '';
var name = req.body.username;
var password = req.body.password;
var email = req.body.email;
db.checkExistingEmail(email, function(data){
if(data === true)
console.log('success');
else
console.log('fail');
});
});
Now When I run this and try registering the functionality I want is not working. I was wondering if is has to go with my checkExistingEmail function and if I am using results.row.email correctly. Right now When I run this code I just keep getting that it has failed. Which is not what I want. it should be returning true for a new user with an email that has never been saved into the db before.
This is usually not the way to go with a database. Checking first always requires two round-trips to the database. Instead,
put a unique constraint on the "email" column,
just insert the data, and
handle the error you'll get with a duplicate email.
Most inserts will just succeed--one round-trip to the database. And you have to handle errors anyway--there's a lot of reasons an INSERT can fail. So there's not a lot of additional code to write for this specific error.

Sending message to a specific connected users using webSocket?

I wrote a code for broadcasting a message to all users:
// websocket and http servers
var webSocketServer = require('websocket').server;
...
...
var clients = [ ];
var server = http.createServer(function(request, response) {
// Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
...
});
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server.
httpServer: server
});
// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
...
var connection = request.accept(null, request.origin);
var index = clients.push(connection) - 1;
...
Please notice:
I don't have any user reference but only a connection .
All users connection are stored in an array.
Goal: Let's say that the Node.js server wants to send a message to a specific client (John). How would the NodeJs server know which connection John has? The Node.js server doesn't even know John. all it sees is the connections.
So, I believe that now, I shouldn't store users only by their connection, instead, I need to store an object, which will contain the userId and the connection object.
Idea:
When the page finishes loading (DOM ready) - establish a connection to the Node.js server.
When the Node.js server accept a connection - generate a unique string and send it to the client browser. Store the user connection and the unique string in an object. e.g. {UserID:"6", value: {connectionObject}}
At client side, when this message arrives - store it in a hidden field or cookie. (for future requests to the NodeJs server )
When the server wants to send a message to John:
Find john's UserID in the dictionary and send a message by the corresponding connection.
please notice there is no asp.net server code invloced here (in the message mechanism). only NodeJs .*
Question:
Is this the right way to go?
This is not only the right way to go, but the only way. Basically each connection needs a unique ID. Otherwise you won't be able to identify them, it's as simple as that.
Now how you will represent it it's a different thing. Making an object with id and connection properties is a good way to do that ( I would definitely go for it ). You could also attach the id directly to connection object.
Also remember that if you want communication between users, then you have to send target user's ID as well, i.e. when user A wants to send a message to user B, then obviously A has to know the ID of B.
Here's a simple chat server private/direct messaging.
package.json
{
"name": "chat-server",
"version": "0.0.1",
"description": "WebSocket chat server",
"dependencies": {
"ws": "0.4.x"
}
}
server.js
var webSocketServer = new (require('ws')).Server({port: (process.env.PORT || 5000)}),
webSockets = {} // userID: webSocket
// CONNECT /:userID
// wscat -c ws://localhost:5000/1
webSocketServer.on('connection', function (webSocket) {
var userID = parseInt(webSocket.upgradeReq.url.substr(1), 10)
webSockets[userID] = webSocket
console.log('connected: ' + userID + ' in ' + Object.getOwnPropertyNames(webSockets))
// Forward Message
//
// Receive Example
// [toUserID, text] [2, "Hello, World!"]
//
// Send Example
// [fromUserID, text] [1, "Hello, World!"]
webSocket.on('message', function(message) {
console.log('received from ' + userID + ': ' + message)
var messageArray = JSON.parse(message)
var toUserWebSocket = webSockets[messageArray[0]]
if (toUserWebSocket) {
console.log('sent to ' + messageArray[0] + ': ' + JSON.stringify(messageArray))
messageArray[0] = userID
toUserWebSocket.send(JSON.stringify(messageArray))
}
})
webSocket.on('close', function () {
delete webSockets[userID]
console.log('deleted: ' + userID)
})
})
Instructions
To test it out, run npm install to install ws. Then, to start the chat server, run node server.js (or npm start) in one Terminal tab. Then, in another Terminal tab, run wscat -c ws://localhost:5000/1, where 1 is the connecting user's user ID. Then, in a third Terminal tab, run wscat -c ws://localhost:5000/2, and then, to send a message from user 2 to 1, enter ["1", "Hello, World!"].
Shortcomings
This chat server is very simple.
Persistence
It doesn't store messages to a database, such as PostgreSQL. So, the user you're sending a message to must be connected to the server to receive it. Otherwise, the message is lost.
Security
It is insecure.
If I know the server's URL and Alice's user ID, then I can impersonate Alice, ie, connect to the server as her, allowing me to receive her new incoming messages and send messages from her to any user whose user ID I also know. To make it more secure, modify the server to accept your access token (instead of your user ID) when connecting. Then, the server can get your user ID from your access token and authenticate you.
I'm not sure if it supports a WebSocket Secure (wss://) connection since I've only tested it on localhost, and I'm not sure how to connect securely from localhost.
For people using ws version 3 or above. If you want to use the answer provided by #ma11hew28, simply change this block as following.
webSocketServer.on('connection', function (webSocket) {
var userID = parseInt(webSocket.upgradeReq.url.substr(1), 10)
webSocketServer.on('connection', function (webSocket, req) {
var userID = parseInt(req.url.substr(1), 10)
ws package has moved upgradeReq to request object and you can check the following link for further detail.
Reference: https://github.com/websockets/ws/issues/1114
I would like to share what I have done. Hope it doesn't waste your time.
I created database table holding field ID, IP, username, logintime and logouttime. When a user logs in logintime will be currect unixtimestamp unix. And when connection is started in websocket database checks for largest logintime. It will be come user logged in.
And for when user logs out it will store currect logouttime. The user will become who left the app.
Whenever there is new message, Websocket ID and IP are compared and related username will be displayed. Following are sample code...
// when a client connects
function wsOnOpen($clientID) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );
require_once('config.php');
require_once CLASSES . 'class.db.php';
require_once CLASSES . 'class.log.php';
$db = new database();
$loga = new log($db);
//Getting the last login person time and username
$conditions = "WHERE which = 'login' ORDER BY id DESC LIMIT 0, 1";
$logs = $loga->get_logs($conditions);
foreach($logs as $rows) {
$destination = $rows["user"];
$idh = md5("$rows[user]".md5($rows["time"]));
if ( $clientID > $rows["what"]) {
$conditions = "ip = '$ip', clientID = '$clientID'
WHERE logintime = '$rows[time]'";
$loga->update_log($conditions);
}
}
...//rest of the things
}
interesting post (similar to what I am doing).
We are making an API (in C#) to connect dispensers with WebSockets, for each dispenser we create a ConcurrentDictionary that stores the WebSocket and the DispenserId making it easy for each Dispenser to create a WebSocket and use it afterwards without thread problems (invoking specific functions on the WebSocket like GetSettings or RequestTicket).
The difference for you example is the use of ConcurrentDictionary instead of an array to isolate each element (never attempted to do such in javascript).
Best regards,

Sending client side form input to server side database query via Node.js and return results to client

I am developing a web application where the user can type in a "device id" on the web page (we have 100's of devices out on the field in production use each with a unique ID), that result entered by the user will be sent to the Node.js server that in return will store it into a variable and use it in a SQL Query to retrieve results about that particular device from the database server and then display the results back to the client web page.
Currently the form input feature has not been implemented yet even though I've already coded the form code in html.
The program works fine as it is if I were to manually change the DEVICE_ID to the device I wish to retrieve data from in the code but of course I want to be able to enter this on the client page instead of me having to change it in the server-side source code manually.
"use strict";
var pg = require('pg').native;
var http = require('http');
var $ = require('cheerio');
var fs = require('fs');
var url = require('url');
var htmlString = fs.readFileSync('index.html').toString();
var parsedHTML = $.load(htmlString);
var dbUrl = "tcp://URL HERE/";
// The Sign-ID
var DEVICE_ID = '2001202';
// Create the http server
http.createServer(function (request, response) {
var request = url.parse(request.url, true);
var action = request.pathname;
// Connect and query the database
pg.connect(dbUrl, function(err, client) {
// The complete sql query for everything that's needed for the app!
client.query("SQL QUERY IS HERE" + DEVICE_ID + "etc..",
function (err, result) {
// Remaining program code is here that performs DOM based
// manipulation to display results returned from the server
// to the client side page.
// Time to Render the document and output to the console
console.log(parsedHTML.html());
// Render the document and project onto browser
response.end(parsedHTML.html());
}
); // End client.query
}); // End pg.connect
}).listen(8080); // End http.CreateServer
pg.end();
I've considered the following:
1) Use An OnClick() function from within the HTML code, like this:
onclick="lookupSignID()
Then include an external JS file from within the HTML that includes the lookupSignID() function however I soon found out this is only performing client-side function and is not what I want.
2) AJAX is only good for if the server is generating new information by itself, therefore I can't use AJAX since the user is entering the device ID to get information from it.
3) Possibly using POST/ GET
Can anyone please advise on what course of action I should take? If solution (3) is the best way how would I go about doing this? Can it be integrated into my existed code (shown above) without many changes?
Thanks!
If you used jQuery on the client side with an AJAX POST function, and then on the server side, you have express.js, you could do this:
app.post('/deviceid', function(req, res) {
var deviceid = req.param('deviceid')
console.log(deviceid)
...
})

Categories

Resources