AngularJS: chat app with socket.io over https

2019-06-20 01:25发布

问题:

I am running this example chat app https://github.com/btford/angular-socket-io-im that uses socket.io/angular/node to make a basic im client.

However I run into trouble when I try to make it work over https.

No socket events are caught on the server, so no chat messages are sent to clients and users can't join rooms. I also get this error on the client in socket.io.js:

Uncaught TypeError: Cannot call method 'onClose' of null  

I've created an express https server listening on port 8000 and modified the socket definition to :

 var socket = io.connect('https://localhost:8000',{secure: true, port:8000});

both in js/services.js and in /bower_components/angular-socket-io/socket.js

Not quite sure how to go about fixing this. Thanks in advance!

回答1:

I have an app that does this exact same thing :) uses socket io and uses :8080 you will need to make sure your security cert is registering that both https://localhost and https://localhost:8000 and has been added to your keychain otherwise the page will load but your socket connections will fail.



回答2:

Only a few changes were required to make it available via https, though this is an old express 2.5 application you should consider looking into: https://github.com/guille/chat-example.git

/**
 * Module dependencies.
 */

var fs = require('fs');
var options = {
  key:fs.readFileSync('key.pem'),
  cert:fs.readFileSync('cert.pem')
};
var express = require('express'),
  routes = require('./routes'),
  socket = require('./routes/socket.js');

var app = module.exports = express.createServer(options);



// Hook Socket.io into Express
var io = require('socket.io').listen(app);

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', {
    layout: false
  });
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.static(__dirname + '/public'));
  app.use(app.router);
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', routes.index);
app.get('/partials/:name', routes.partials);

// redirect all others to the index (HTML5 history)
app.get('*', routes.index);

// Socket.io Communication

io.sockets.on('connection', socket);

// Start server

app.listen(8080, function(){
  console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});