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.
Related
I am using websocket and http server together, assigning each of them a different port, when a post request hits it sends a message to client using websocket and response of http request is send when client responds to the message.
My problem is I want to create multiple websockets but a single https server, I have tried some things but unable to do it.
Current code for creating websocket and httpserver is
const app = require('express')()
bodyParser = require('body-parser')
app.use(bodyParser.json())
const net = require('net');
var client;
var res1,currentReq;
//----------------------------------------------------------------------------
// http requests listener
//----------------------------------------------------------------------------
app.listen(8001, () => console.log('Http server listening on port 8001'));
//----------------------------------------------------------------------------
// http requests handling
//----------------------------------------------------------------------------
app.post('/getUser', (req, res) => {
console.log(req.body)
res1 = res;
currentReq='getUser';
client.write('{"route":"/","data":{"username":"' + req.body.username +'"}, "res": "' + res + '"}');
//res.end('{"Extension":"' +' data '+ '"}');
console.log("/getUser finished");
// res.end('{"Extension":"' +' data '+ '"}');
});
//----------------------------------------------------------------------------
// Establishing tcp connection for incoming requests
//----------------------------------------------------------------------------
var server = net.createServer(function(connection) {
console.log ('client has connected successfully!');
client = connection;
client.on('data',function(data){
switch(currentReq)
{
case 'getUser' :
console.log('send get user response');
res1.end(data);
break;
}
console.log(data.toString());
//res1.end(data);
});
connection.pipe(connection);
});
//----------------------------------------------------------------------------
// listener for tcp connections
//----------------------------------------------------------------------------
server.listen(8000, function() {
console.log('server for localhost is listening on port 8000');
console.log('server bound address is: ' + server.address ());
});
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");
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
I have a simple client server web app that is using web sockets to send / receive information. The client can connect and receives properly the config file but then when I try to send a "test' message from the client using "socket.emit('message', {my: 'data'});" it doesn't display on the server. I did check with wireshark and the packets are arriving at the server.
var sIoPort = 8181;
var host = '192.168.4.111';
var fs = require('fs');
var iniMsg = fs.readFileSync('data.json','utf8');
var http = require("http").createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
http.listen(sIoPort,host);
var browserServer = require('socket.io').listen(http);
browserServer.on('connection', function (socket) {
console.log('Client websocket connected');
// send the config file if available
browserServer.sockets.emit('msg',iniMsg.toString());
});
browserServer.on('message', function (message) {
console.log('received message: ' + message);
});
client side
///////////////////////////////////////////////////////////////////////////////
socket = io.connect("192.168.4.111",{"port":8181});
socket.on('connect',function() {if(DEBUG) console.log('Socket Connected');});
socket.emit('message', {my: 'data'}); // test if server receives message
socket.on('msg',function(data) {
var json = JSON.parse(data);
// add the maps to the the GUI
switch(json.type) {
case 'maps': add_maps_from_json(json, null);
break;
}
});
socket.on('disconnect',function() {if(DEBUG) console.log('Socket Disconnected');});
/////////////////////////////////////////////////////////////////////////////////
Modify the serverside listener so it's paying attention to events on a socket:
browserServer.on('connection', function (socket) {
console.log('Client websocket connected');
// send the config file if available
browserServer.sockets.emit('msg',iniMsg.toString());
socket.on('message', function (message) {
console.log('received message: ' + message);
});
});
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));
});