Created a sample scalable application using nodejs connected with mysql database in openshift . But I got 502 error bad gateway.changed #option httpchk GET / in haproxy.
I have a database testnodejs having table users(id int,name varchar);
my sample code
index.html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function () {
$.get('/users',data,function(data){
});
});
});
</script>
</head>
<body>
<h3>Enter a username</h3>
<input id="user" type="text" />
<input id="submit" type="submit" />
<p id="output"></p>
</body>
</html>
app.js
var express = require('express'),
mysql = require('mysql');
var ipaddr = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
var app = module.exports = express.createServer();
var connection = mysql.createConnection({
host : process.env.OPENSHIFT_MYSQL_DB_HOST,
user : process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password :process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
port :process.env.OPENSHIFT_MYSQL_DB_PORT,
db :"testnodejs"
});
app.use(express.bodyParser());
connection.connect();
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/users', function(req, res){
connection.query("select * from users where name="+req.query["name"],
function(err, result, fields) {
if (err) throw err;
else {
res.send(result);
}
});
});
app.listen(port,ipaddr);
console.log("Express server listening on port %d in %s mode",port, ipaddr, app.settings.env);
Related
So I'm trying to host a web app using node.js express and my server.js seems to hang upon using npm start. In my package.json file it calls node server.js and everything starts properly but my website won't deploy to the local host for me to view. I have a feeling it is either something to do with the location of my css/index.html or it could be something with the way i create the request from the client side from index.html I'm new to backend, so really out in the deep on this one.
//1.) create http server
const PORT = process.env.PORT || 2525;
const INDEX = '/public/index.html';
const express = require('express')
var server = express();
console.log(__dirname)
server.use(express.static(__dirname + "/public"));
server.get('public/index.html', function(req, res, next) {
res.sendFile(__dirname + INDEX);
});
server.listen(PORT);
//2.) Create a websocket server
const { Server } = require('ws');
const wss = new Server({ server });
//3.) Handle connections
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('close', () => console.log('Client disconnected'));
});
//4.) Boradcast updates
setInterval(() => {
wss.clients.forEach((client) => {
client.send(new Date().toTimeString());
});
}, 1000);
console.log('Server started at http://localhost:' + PORT);
This is my index.html below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>am i sheep</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div>
<span>
<h3> Am I Sheep<h3>
</span>
</div>
<div>
</div>
<div>
<input type="file" id="fileID" hidden></input>
<label for='fileID'>select image</label>
</div>
<div>
<h1 id='server-time'>current time</h1>
<script>
var HOST = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(HOST);
var el;
ws.onmessage = function (event) {
el = document.getElementById('server-time');
el.innerHTML = 'Server time: ' + event.data;
};
</script>
</div>
</body>
</html>
UPDATE:
So the issue that seems to be popping up now is
WebSocket connection to 'ws://localhost:2525/' failed
var ws = new WebSocket(HOST);
So the error is happening between the handshake between the client and server
The server.js
//1.) create http server
const PORT = process.env.PORT || 2525;
const INDEX = "/public/index.html";
const express = require("express");
const { createServer } = require("http");
const app = express();
const httpServer = createServer(app);
// Static files
app.use(express.static(__dirname + "/public"));
app.get("/", function (req, res, next) {
res.sendFile(__dirname + INDEX);
});
//2.) Create a websocket server
const { Server } = require("ws");
const wss = new Server({ server: httpServer });
//3.) Handle connections
wss.on("connection", ws => {
console.log("Client connected");
ws.on("close", () => console.log("Client disconnected"));
});
//4.) Boradcast updates
setInterval(() => {
wss.clients.forEach(client => {
client.send(new Date().toTimeString());
});
}, 1000);
httpServer.listen(PORT, () => console.log("Server started at http://localhost:" + PORT));
The index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>am i sheep</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div>
<span>
<h3> Am I Sheep<h3>
</span>
</div>
<div>
</div>
<div>
<input type="file" id="fileID" hidden></input>
<label for='fileID'>select image</label>
</div>
<div>
<h1 id='server-time'>current time</h1>
<script>
var HOST = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(HOST);
var el;
ws.onopen = function () {
alert('Connection Open');
};
ws.onerror = function (error) {
alert('Error');
};
ws.onmessage = function (event) {
el = document.getElementById('server-time');
el.innerHTML = 'Server time: ' + event.data;
};
</script>
</div>
</body>
</html>
I'm fairly new to Nodejs and I'm building an app that ssh to a remote machine and get a tail -f of a log file.
The lines of the log file I'm receiving I'm sending to the client via socket-io (ver. 2.0.3)
Now I'm facing a problem that when a second browser tries to tail a different log, the new log is sent to both of the browsers instead of only the one who made the request.
I'm not sure if it's a problem with my socket-io code or the child_process.
Here's the server:
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn,
events = require('events'),
eventEmitter = new events.EventEmitter();
// Fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
eventEmitter.on('tail', (data) => {
socket.tail = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], { shell: true });
socket.tail.stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
socket.emit('newLine', {line: data.toString().replace(/\n/g, '<br />')});
});
});
});
app.get('/tail', (req, res) => {
eventEmitter.emit('tail', req.query);
res.sendStatus(200);
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
$.get('/tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
Server
const express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser'),
logger = require('morgan'),
server = require('http').Server(app),
io = require('socket.io')(server),
spawn = require('child_process').spawn;
// Fix body of requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Log the requests
app.use(logger('dev'));
// Serve static files
app.use(express.static(path.join(__dirname, '.')));
// Add a basic route – index page
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
var tails = {};
io.on('connection', (socket) => {
console.log(`client connected ${socket.client.id}`);
socket.on('tail', (data) => {
socket.join(data.service);
if (typeof tails[data.service] == "undefined") {
tails[data.service] = spawn('ssh', ['root#' + 'quality-p.company.com', 'tail -f', data.service], {
shell: true
});
tails[data.service].stdout.on('data', (data) => {
console.log(`got new data ${data.toString()}`);
io.to(data.service).emit('newLine', {
line: data.toString().replace(/\n/g, '<br />')
});
});
}
});
});
// Bind to a port
server.listen(3005, () => {
console.log('running on localhost:' + 3005);
});
Client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(() => {
let socket = io();
socket.on('connect', () => {
console.log('connected');
});
socket.on('newLine', (data) => {
console.log(`new data: ${data.line}`);
$("#tailing").append(data.line);
});
$('#tail').click(() => {
socket.emit('tail', {
service: $('#service').val()
});
});
});
</script>
<title>Title</title>
</head>
<body>
<select id="service">
<option id="tnet" value="/var/log/tnet">tnet</option>
<option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>
I am studying node and express. I have a table of inventory item and I want to view this on my web browser that's why I used socket.io with express.
But when there's a connection I can't load the data. Here's my code:
server.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 8000;
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'node'
});
app.use(express.static(__dirname + '/public'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
connection.connect();
/**example from express
connection.connect();
connection.query('SELECT * FROM inventory', function(err, rows, fields){
if(err) throw err;
console.log(rows);
});
connection.end();
**/
function loadList() {
connection.query('SELECT * FROM inventory', function(err, rows, fields){
if(err) throw err;
return rows;
});
}
io.on('connection', function(socket){
console.log('A user is connected!!');
socket.on('inventory list', function(data){
return 'hello world'; // i pass a simple return to test if this can return something
/*
connection.query('SELECT * FROM inventory', function(err, rows, fields){
if(err) throw err;
console.log(rows);
});
*/
});
socket.on('disconnect', function() {
console.log('user disconnected!');
});
});
http.listen(8000, function() {
console.log('Listening on ' + port);
});
index.html
<!DOCTYPE>
<html>
<head>
<title>Invertory Sample</title>
<link rel="stylesheet" type="text/css" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/bower_components/font-awesome/css/font-awesome.min.css" />
</head>
<body>
<p>sample</p>
<p class="test"></p>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
try {
var socket = io.connect('http://127.0.0.1:8000');
//console.log(socket);
}catch(e) {
console.log('ERROR OCURRED: ' + e);
}
if(socket !== undefined) {
socket.on('inventory list', function(data) { console.log(data); //i console but no response. });
}
</script>
</body>
</html>
Can you help me? I am extremely new in nodejs but I have some basic understanding. Or can you provide me a good example for this?
Thats all thanks.
In both, client and server, your are listening an event('inventory list'), but no one emits this event.
If you want to send the list to the client on conection you can try something like this on server:
io.on('connection', function(socket){
console.log('A user is connected!!');
socket.emit('inventory list', { list: 'mylist' });
socket.on('disconnect', function() {
console.log('user disconnected!');
});
});
http://socket.io/docs/server-api/
I am trying to send a message from a input field in a html form to all clients connected to the server when one of the clients posts something in the input field (textbox). I want to use the socket.write function because I have a raw TCP client connected to the server.
I tried to use the Express library with the Post event because I want that kind of behaviour but can't use socket e.g. socket.write function inside of the app.post function.
Here is what I currently have on the server side:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var net = require('net');
var server = net.createServer(function (socket) {
socket.write(' + req.body.name + ');
socket.pipe(socket);
});
app.get('/', function(req, res){
res.sendfile('index.html');
});
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
//How to do this here??
server.socket.write(' + req.body.name + ')
socket.end();
});
app.listen(3000, function() {
console.log('Server running at http://127.0.0.1:3000/');
});
//Thought of using a different server port for the raw TCP device
server.listen(2000, '127.0.0.1');
And a html form on the client side:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Form</title>
</head>
<body>
<div id="contact">
<h1>Send an email</h1>
<form action="http://127.0.0.1:3000/myaction" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Your name" />
<label for="email">Surname:</label>
<input type="text" id="surname" placeholder="Your surname" />
<input type="submit" value="Send" />
</fieldset>
</form>
</div>
</body>
</html>
Is there a way to do the socket.write on the app.post event. And can the name from the input field be sent using socket.write.
Sorry if i am missing something, I am new to this kind of programming.
You need to keep track of your TCP clients. Try this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var net = require('net');
// All your clients
var clients = [];
var server = net.createServer(function (socket) {
// Track the client
clients.push(socket);
socket.on('data', function (data) {
// Handle data coming from clients here
});
});
app.get('/', function(req, res){
res.sendfile('index.html');
});
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
broadcast('New name:' + req.body.name);
});
// Here's where you send data to all clients
function broadcast(msg) {
clients.forEach(function (client) {
client.write(msg);
});
}
app.listen(3000, function() {
console.log('Server running at http://127.0.0.1:3000/');
});
//Thought of using a different server port for the raw TCP device
server.listen(2000, '127.0.0.1');
I have a group chat app. When client login with his email and password, he would be directed to chat page with his name on top and he would able to chat with online user.How can my app. identify from which user message was sent. One possibility is to send socket.id along with message to server for identifying user but socket.id get changed on refreshing the page.
login.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/loginstyle.css" />
</head>
<body>
<form class="css" method="post" action="http://192.168.1.3:9373/valid" >
<fieldset >
<input type="text" name="email" class="inputemail" placeholder="Email" />
</fieldset>
<fieldset >
<input type="password" name="pass" class="inputpassword" placeholder="Password" />
</fieldset >
<fieldset >
<button type="submit" class="submit">Submit</button>
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://192.168.1.3:9373');
</script>
</body>
</html>
chat.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="name"> Welcome </div>
<br></br>
<div class="chat"></div>
<form>
<input type="text" class="msg"> </input>
<button type="submit" class="enter">Send</button>
<input type="file" class="file"></input>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
var socket = io.connect('http://192.168.1.3:9373');
var online=[];
var checkFile=0;
$.get("/getName", function(string){
username=string;
$('.name').append(username);
});
$('.enter').bind("click",function(){
$.get("/getMsg", function(){
setTimeout (function(){
socket.emit('chat message',$('.msg').val() );
$('.msg').val('');
},0);
});
return false;
});
socket.on('chatmessage', function(name,msg){
var block= $("<div class='message'> </div>");
if(msg.length){
var messenger= $("<div class='messenger'> </div>");
messenger.append(name);
block.append(messenger);
var text;
text=$("<div class='text'></div>");
text.append(msg);
block.append(text);
block.append($("<div class='pad'></div>"));
$('.chat').append(block);
}
});
});
</script>
</body>
</html>
server.js
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, Twit = require('twit')
, io = require('socket.io').listen(server)
, os = require('os')
, open = require('open')
, bodyParser = require('body-parser')
, connect = require('connect')
, cookieParser = require('cookie-parser')
, session = require('express-session')
, sessionStore = session.MemoryStore()
, async = require('async')
, mysql = require("mysql");
var id=[];
var a;
server.listen(9373,'192.168.1.3');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser("secret"));
app.use(session({
store: sessionStore,
secret: "54321",
saveUninitialized: true,
resave: true
}));
app.get('/loginme', function (req, res) {
res.sendfile(__dirname + '/loginmysql.html');
});
app.get('/option', function (req, res) {
res.sendfile(__dirname + '/option.html');
});
app.get('/getName', function (req, res) {
var r = {};
r.name = req.session.userid;
res.send(r.name);
});
app.get('/getMsg', function (req, res) {
a = req.session.id;
res.json(a);
});
app.get('/chat', function (req, res) {
res.sendfile(__dirname + '/chat.html');
});
app.post('/valid', function (req, res) {
var username=req.body.email;
var password=req.body.pass;
var connection = mysql.createConnection({
"hostname": "localhost",
"user": "root",
"password": "vk123",
"database": "login"
});
connection.connect();
connection.query('SELECT * FROM id WHERE email=? AND password=?', [username,password], function(err, rows){
if (err){
throw err;
}else{
var name=rows[0].name;
req.session.userid = name;
id.push({sid:req.session.id, username:req.session.userid});
res.redirect('http://192.168.1.3:9373/option');
io.sockets.on('connection', function (socket){
io.emit('name',name);
});
}
});
connection.end();
});
io.sockets.on('connection', function (socket){
socket.on('chat message', function(msg){
var user;
var i;
for(i=id.length-1; i>=0; i--){
if(id[i].sid == a){
user=id[i].username;
break;
}
}
io.emit('chatmessage',id[i].username,msg);
});
});
app.use(express.static(__dirname+'/public'));