Why express.vhost isn't working? - node.js

I create 3 node js servers.I'm trying to load server2 and server3 into server1.I'm trying with express.vhost but i can't succed.Here is my code:
server:
var application_root = __dirname,
express = require( 'express' ),
vhost = require( 'vhost' );
function createVirtualHost(domainName, dirPath) {
return vhost(domainName, express.static( dirPath ));
}
//Create server
var app = express();
//Create the virtual hosts
var host1 = createVirtualHost("http://localhost:8001", "/");
var host2 = createVirtualHost("http://localhost:8002", "/");
//Use the virtual hosts
app.use(host1);
//app.use(host2);
//Start server
var port = 80;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
server 1 :
var http = require('http');
//Lets define a port we want to listen to
const PORT=8001;
//We need a function which handles requests and send response
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
module.exports=server;
server 3:
var http = require('http');
//Lets define a port we want to listen to
const PORT=8002;
//We need a function which handles requests and send response
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
I have these files in the same folder.Thanks for any help!

Related

Node.JS Express - POST request not working (returning 404) - running in sub-directory on port 8080

I have 2 node.js servers running;
1 on port 8000
another on port 8080
The one on port 8080 will be an API, so need to send POST requests to it.(Endpoint: websocket/test).
When I try to do this, a 404 gets returned.
It is sat in a subdirectory(ROOT/webhook), so not sure if that is the reason, or if its the fact that it is on port 8080?
Socket.io is working fine and connects with no issues, I just cant send a POST request to this server.
Here is the server.js file:
//SOCKET.IO Server
const express = require('express');
const app = express();
const port = 8080;
const fs = require('fs');
const http = require('http');
const https = require('https');
const sslKey = 'HIDDEN';
const sslCert = 'HIDDEN';
const options = {
key: fs.readFileSync(sslKey),
cert: fs.readFileSync(sslCert)
};
const httpServer = http.createServer();
const httpsServer = https.createServer(options);
const io = require('socket.io')(httpsServer);
// FOR HTTP
// httpServer.listen(port, () => {
// console.log("Socket.io http server is listening on port: " + port)
// console.log(__dirname + '/key.pem');
// })
// FOR HTTPS
httpsServer.listen(port, () => {
console.log("Socket.io https server is listening on port: " + port);
})
io.on('connection', function(socket){
console.log('made socket connection', socket.id);
socket.emit('welcome', 'Hiya! Welcome');
app.post('/websocket/test', function() {
console.log('webhook received');
io.emit('webhook', 'You have received a webhook!');
});
});
You almost got everything right. Except you aren't telling your express application to start listening for requests. By just changing this code:
const httpsServer = https.createServer(options);
to this:
const httpsServer = https.createServer(options, app);
Your server should work.

Talking AWS Servers (EC2)

I am trying to get two EC2 instances to talk; but, I am running into a block. I am not sure what IP address and port to use, and also am wondering if I need to change any of the server/client code now that they aren't talking on the same machine. Security Groups are allowing inbound traffic on ports 22,80, and 60201.
When I use port 60201, i get EADDRNOTAVAIL.
Here is the config file.
Host wmnode
User ubuntu
IdentityFile ~/.ssh/wmnode
HostName 52.4.212.112
Host mvclient
User ubuntu
IdentityFile ~/.ssh/mvclient
HostName 107.21.65.254
Here is server.js
const port = 60201;
const ipAddress = "52.4.212.112"
var http = require('http');
var io = require('socket.io');
var server = http.createServer();
server.listen(port, ipAddress);
var socket = io.listen(server);
socket.on('connection', (serverSocket) => {
console.log('connected to 52.4.212.112');
serverSocket.on('clientEvent', function (data) {
console.log('message from the server:', data);
serverSocket.emit('serverEvent', "thanks for sending '" + data + "'");
});
});
And here is client.js
const port = 60201;
const ipAddress = "52.4.212.112";
const url = 'http://' + ipAddress + ':' + port;
var io = require('socket.io-client');
var socket = io(url);
socket.on('connect', () => {
socket.on('serverEvent', function (data) {
console.log('new message from the server:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent from the client');
}, 3000);
});

Node js, Call WebSocket server from http server

I have a node js ( supported by express js ) http application. So I had a server.js file as follows(not there complete code).
var app = require('./app/app');
var server = http.createServer(app);
server.listen(port, host);
server.on('error', onError);
server.on('listening', onListening);
I later added websocket server to there. So it is like this now.
// app server
var app = require('./app/app');
var server = http.createServer(app);
server.listen(port, host);
server.on('error', onError);
server.on('listening', onListening);
/**
* websocker Server
*/
var WebSocket = require('ws');
var wsServer = http.createServer();
var url = require('url');
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ server: wsServer });
var express = require('express');
var wsApp = express();
var port = 1337;
wsApp.use(function (req, res) {
res.send({ msg: 'hello' });
});
wss.on('connection', function connection(ws) {
console.log((new Date()) + ' Connection from origin ');
ws.on('message', function incoming(message) {
console.log('received: %s', message);
var json = JSON.stringify({ type:'message', data: {hello : 'hello'} });
ws.send(json);
});
var json = JSON.stringify({ type:'message', data: {hello : 'hello'} });
ws.send(json);
});
wsServer.on('request', wsApp);
wsServer.listen(port, function () { console.log('Ws server Listening on ' + wsServer.address().port); });
Now these two are working happily. What I want is on a POST call to the http server, I want to trigger the web socket server to broadcast something to all clients. My problem is How I can trigger websocket server from http server?
Routes of http server is defined in app.js file. from there how can I call websocker server function?
If you encapsulate your ws functionality in one single javascript file (e.g: websocket.js) you could export your websocket object as a module.
module.exports = wss;
and then require it in your http controller
var wss = require(websocket.js)
In this case it should be easy to use wss.send({...}) wherever you like.
This peace of code is working to me:
//websocket.js
'use strict';
var io = require('socket.io');
var callme;
function Websocket(server) {
var server = io(server);
server.on('connection', function(socket){
console.log('Do something here');
});
callme = function (val) {
//you my choose a specific cliente if you want, read the socket.io doc
server.emit('I may emit it ' + val);
console.log("Called " + val);
return 'Somebody got it';
}
}
Websocket.route = function(req, res, next) {
if(typeof callme == 'function'){
res.send(callme(req.param('t')));
}else{
res.send('Websocket server is not running');
}
};
module.exports = Websocket;
On the express app definition, I put
var Websocket = require('./websocket');
app.use('/blablabla', Websocket.route);
Then, on the server js file, which run the application, I put
var server = http.createServer(app);
var s = new Websocket(server);
This last line works like the tradicional io(server); would work.
After that, when you request the address /blablabla the route will execute your websocket method.
My solution is not in production yet, let me know if somebody got an error.

Conditional port forwarding by hostname

I'm a newbie to node-http-proxy module.
my aim
I need to use the module provide multi-SSL for multi-subdomain.
For example;
if a user call process.localhost:1443 then I should route the call to process.localhost:2443 and
if a user call api.localhost:1443 then I should route the call to api.localhost:3443
what's happening
I wrote the below server.js codes. However when I try to call process.localhost:1443 I get the following error;
D:\Work Space\...\http-proxy\node_modules\requires-port\index.js:13
protocol = protocol.split(':')[0];
TypeError: Cannot call method 'split' of undefined
protocol seems as undefined.
function required(port, protocol) {
protocol = protocol.split(':')[0];
What should I do?
server.js
var fs = require('fs'),
httpProxy = require('http-proxy'),
express = require('express'),
app = require('./app').service,
api = require('./api').service;
// PROXY
var options = {
changeOrigin: true,
forward: {
'process.localhost': 'process.localhost:2443',
'api.localhost' : 'api.localhost:3443'
}
}
httpProxy.createServer(options).listen(1443, function() {
console.log('Proxy is listening on port 1443')
})
// HTTP
app
.listen(2443, function() {
console.log('PROCESS APP server is listening on port 2443')
})
api
.listen(3443, function() {
console.log('API APP server is listening on port 3443')
})
I could solve this issue through someone from node-http-proxy forum.
var proxyTable = {}
proxyTable['api.localhost:1443'] = 'http://127.0.0.1:3443'
proxyTable['process.localhost:1443'] = 'http://127.0.0.1:2443'
var proxy = httpProxy.createServer({changeOrigin: true})
var http = require('http')
http.createServer(function(req, res) {
var options = {
target: proxyTable[req.headers.host]
}
proxy.web(req, res, options)
}).listen(1443, function() {
console.log('Proxy server is listening on port 1443')
})
app.listen(2443, function() {
console.log('APP server is listening on port 2443')
})
api.listen(3443, function() {
console.log('API server is listening on port 3443')
})

node.js listen for UDP and forward to connected http web clients

I'm new to node.js, so forgive the ignorance if this is simple.
What I want to do is setup a simple node.js http server to which a web-client connects. I also want the node.js server to act as a UDP listener on a separate port, on which it will receive JSON payloads from some other application. I want the node.js server to then forward these JSON payloads immediately to one or more of the connected web-clients.
I got this far from some initial googling around:
Create a simple node.js http server that responds with a static html page:
//Initialize the HTTP server on port 8080, serve the index.html page
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
}).listen(8080, function() {
console.log('Listening at: 127.0.0.1 8080');
}
);
Initialize a UDP server on a separate port:
//Initialize a UDP server to listen for json payloads on port 3333
var srv = dgram.createSocket("udp4");
srv.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
io.sockets.broadcast.emit('message', 'test');
//stream.write(msg);
//socket.broadcast.emit('message',msg);
});
srv.on("listening", function () {
var address = srv.address();
console.log("server listening " + address.address + ":" + address.port);
});
srv.bind(5555);
Use socket.io to establish a live connection between web-client and server:
//this listens for socket messages from the client and broadcasts to all other clients
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg.data.skeletons[0] ? msg.data.skeletons[0].skeleton_id : '');
socket.broadcast.emit('message', msg);
}
);
});
I guess my problem is I don't know how to bridge 2 and 3, to get the received UDP packets broadcasted to the connected socket.io clients. Or perhaps there's a simpler, more elegant way of doing this? I found the documentation for socket.io to be lacking...
EDIT: thanks to the person that fixed the code formatting
I made a running example for you to get going with: http://runnable.com/UXsar5hEezgaAACJ
For now it's just a loopback client -> socket.io -> udp client -> udp server -> socket.io - > client.
here's the core of it:
var http = require('http');
var fs = require('fs');
var html = fs.readFileSync(__dirname + '/index.html');
//Initialize the HTTP server on port 8080, serve the index.html page
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'
});
res.end(html);
}).listen( process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP, function() {
console.log('Listening');
});
var io = require('socket.io').listen(server);
io.set('log level', 0);
io.sockets.on('connection', function (socket) {
socket.emit('message', 'connected');
socket.on('message', function (data) {
console.log(data);
var address = srv.address();
var client = dgram.createSocket("udp4");
var message = new Buffer(data);
client.send(message, 0, message.length, address.port, address.address, function(err, bytes) {
client.close();
});
});
});
var dgram = require('dgram');
//Initialize a UDP server to listen for json payloads on port 3333
var srv = dgram.createSocket("udp4");
srv.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
io.sockets.emit('message', 'udp');
});
srv.on("listening", function () {
var address = srv.address();
console.log("server listening " + address.address + ":" + address.port);
});
srv.on('error', function (err) {
console.error(err);
process.exit(0);
});
srv.bind();

Resources