using https with express io - javascript

So I am new to express and io but I had a server running fine for webRTC but now there is a deprecated method in webRTC that only runs on https so I tried to create an https server but it starts and then immediately exits. I cannot figure out what is wrong and I do not get any errors. Also I am using an aws ec2 to run the express io server. Maybe someone can spot where in my syntax/implementation I am going wrong.
Note I have been googling around for the past half hour and cannot figure it out
Here is the code:
var connect = require('connect');
var https = require('https');
var fs = require('fs');
var express = require('express.io');
var app = express();
//app.http().io();
var PORT = 443;
var options = {
key: fs.readFileSync('../server.key'),
cert: fs.readFileSync('../server.crt')
};
app.https(options).io();
//var app = https.createServer(options, app1);
console.log('server started on port ' + PORT);
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('index.ejs');
});
app.listen(PORT);
app.io.route('ready', function(req) {
req.io.join(req.data.chat_room);
req.io.join(req.data.signal_room);
app.io.room(req.data).broadcast('announce', {
message: 'New client in the ' + req.data + ' room.'
})
})
Update
I am putting a bounty on this because I would like someone to provide me with a complete answer on setting up the server for production.

You need to add a rule for port 443 in a Security Group for your instance.
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html might help.

Related

How do i fix this error: localhost/:1 Failed to load resource: the server responded with a status of 404 (Not Found), Cannot Get /

I'm creating an online multiplayer .io game similar to https://diep.io/ or https://agar.io/ and I'm in the process of setting up a server this is my code,
var path = require('path');
var http = require('http');
var express = require('express');
var socketIO = require('socket.io');
var publicPath = path.join(__dirname, '../client');
var port = process.env.PORT || 2000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
app.use(express.static(publicPath));
server.listen(port, function () {
console.log('Server stared on port ' + port);
});
When I start the server and put "localhost:2000" into the search bar this is what comes up,
I'm kinda new to this so if you could make the answers simple to understand then I'd really appreciate it.
Double check your paths. Your code will work as written if you have a folder structure like so:
/server/index.js
/client/index.html
$ node server/index.js
The static middleware by default will serve files which match html, html.
So if you have index.html, you can make a request to /, and if you have hello.html, you can hit it at /hello.
See here for more options: http://expressjs.com/en/resources/middleware/serve-static.html
Note: this middleware is what Express.static uses, so no need to install that package, just look at examples for serveStatic() and pass those to Express' version.

What do I replace "http://localhost:3000" with when using a server and not local machine?

I've been doing a lot of online courses with node and express. I want to get sockets.io to work but I can't even establish a connection at the moment. I am using a cPanel virtual private server and running code in the server terminal and then trying to use a website hosted on the server to access the .js file running on the server.
I've tried all sorts of different things but I'm reducing it to its most basic level to try get a connection. All the videos I've seen are running on a local machine and using the command prompt on a local machine to run the .js file and the browser to access http://localhost:3000.
The .js file I'm running on my cPanel server looks like this;
var express = require('express');
var app = express();
app.get('/', function(req,res){
res.send('Hello world 2');
})
app.listen(3000);
So how do I then access that via the browser? I have tried http://mywebsite.com:3000 and http://11.22.33.444:3000 if 11.22.33.444 is the server ip, but the browser just times out and there is no output in the server console.
ultimately I need to run a socket.io command that looks like this;
var socket = io.connect('http://localhost:3000');
and in all the tutorials I've seen they use this localhost:3000 but no one explains how to access this if its on an actual server so I'm pretty lost.
There are other examples like;
...
const http = require('http').createServer();
...
http.listen(3000 => () => {
console.log('listening on port 3000');
});
That's just a snippet of the code but I'm wondering how I then access that 3000 port from the browser without http://localhost:3000
IF you read the docs you will see that there is a guide how to connect it with express: https://socket.io/docs/
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
// WARNING: app.listen(3000) will NOT work here!
app.get('/', function (req, res) {
res.status(200).json({ message: "Connected" });
});
io.on('connection', function (socket) {
console.log("somebody connected");
});
Think I just solved it. I tried a different port and it worked :/
No need to specify any address in io.connect()
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
http.listen(process.env.PORT || 3000, function() {
});
<script src="/socket.io/socket.io.js"></script>
var socket = io.connect();

Socket.io 404 Not Found

For some reason I keep getting "http://127.0.0.1:3000/socket.io/socket.io.js" 404 not found when I look under chrome developer tools network. I have spent over an hour trying to understand why this isn't working because it was working fine before and I didn't think I changed anything.
Server:
var express = require('express'),
session = require('express-session');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var MongoStore = require('connect-mongo')(session);
var sessionMiddleware = session({
resave: false,
saveUninitialized: false,
secret: 'secret',
store: new MongoStore({url: "mongodb://localhost:27017/database"})
});
app.use(sessionMiddleware);
io.use(sessionMiddleware, function(socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
io.sockets.on('connection', function (socket) {
console.log("Socket connected");
});
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index');
});
app.listen(3000);
console.log('listening');
Pug File:
html
head
script(src="http://127.0.0.1:3000/socket.io/socket.io.js")
script(type='text/javascript', src='../javascripts/chat.js')
body
Client javascript:
try {
var socket = io.connect('http://127.0.0.1:3000');
} catch(e) {
console.log(e);
}
Change this:
app.listen(3000);
to:
server.listen(3000);
app.listen() creates a new and different server so the server that you have socket.io attached to is not the one that is actually listening and thus your socket.io server is not live and not able to handle the /socket.io/socket.io.js request or the incoming connection if the script file didn't first fail to load.
See this answer for more details on what app.listen() does and why it isn't what you want the way your code is laid out:
websockets, express.js and can’t establish a connection to the server
Note, you could use app.listen(), but you'd have to not create your own server and you'd have to capture the return value from app.listen() and use that as the server you pass to socket.io initialization:
var app = express();
var server = app.listen(3000);
var io = require('socket.io')(server);
Which is not quite how your code is structured (but you could rearrange things to do it this way).

Winjs app cant connect nodejs socket.io server

I'm build an WP app using HTML5/js/CSS, and today i got a problem. I create a NodeJs server using socket.io fot chat. My server code:
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var mongodb = require('mongodb');
var url = 'mongodb://localhost:27017/chat';
var MongoClient = mongodb.MongoClient;
app.configure(function(){
app.set('port', process.env.PORT || 3456);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = require('socket.io').listen(server)
, guestNumber = 1
, nickNames = {}
, numuser = 0;
io.set('log level', 1);
io.on('connection', function (socket) {
...
});
In my app, i use: var socket = io.connect('myipserver:3456/');
IT NOT CONNECT to my server, but when i use browser to connect my ip server, it normal, and in my app, it got error: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
In package.appxmanifest, i checked Internet ( Client & Server ) Capabilities.
So, do i miss something in my app ? Plz help.
After some Googling I saw this question that has the same error code as your app. Seems to me that this error code says that the app does not see the server. So I don't think it's a socket-related error.
Try making a simple AJAX request to your server (with jQuery: $.get(myipserver:3456/some-static-file)). If it works, then it's something with the socket communications, otherwise the app does not see the server at all. Good point to start from, I guess.

node.js / Https with express

I try to use express in node.js with https.
Here the relevant code for this parts:
var express = require("express");
var app = express();
var https = require('https');
var privateKey = fs.readFileSync('./sslcert/mykey.key', 'utf8');
var certificate = fs.readFileSync('./sslcert/mssl.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
https.createServer(credentials, app).listen(5008, function(res){
console.log("Listen to: " + port)
});
In the console, it prints Listen to: 5008, but I don't see that my server get any request, even though I sent some.
When I use express without the ssl extension, everything works fine.
EDIT:
Here the code which works OK with port 5008, but without the ssl part:
var express = require("express");
var app = express();
app.listen(5008, function () {
console.log("Listening on " + port);
});
What I do wrong?
You have to specify https://, otherwise the browser/client will not know to use SSL when connecting, no matter what port is used (the default of 443 or otherwise).

Categories

Resources