socket.io server - express error in log “no routes

2019-08-24 14:11发布

问题:

Im setting up a chat server with socket.io. I followed their tutorial til it came to SSL. I found some explainations here on stack and tutorials in the net, so i came up with the following code.

I replaced my real domain with "my-domain.de"

var app = require('express')();
var fs = require('fs');
var https = require('https');
var io = require('socket.io')(https);
var mysql = require('mysql');

var options = {
    key: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/privkey.pem'),
    cert: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/cert.pem'),
    ca: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/chain.pem')
};

var serverPort = 8443;
var server = https.createServer(options, app);

server.listen(serverPort, function(){
    console.log('listening on *:' + serverPort);
});


io.on('connection', function(socket){
    console.log('a user connected');

});

The Server runs, but the Client doesnt recieve the socket.io.js. So i started the server with DEBUG=* -node index.js to see whats happening. It shows the following Error when a client tried to connect:

express:application no routes defined on app +9s
finalhandler default 404 +0ms

The Client looks like this:

<script src="https://my-domain.de:8443/socket.io/socket.io.js"></script>
<script>
    $(function () {
        var socket = io('https://my-domain.de:8443/');
</script>

回答1:

After hours of headache i found the solution and it is as simple as always...

I simply had to place var io = require('socket.io')(server); after var server = https.createServer(options, app); So that it can route correctly...

So that my final server code looks like this:

var app = require('express')();
var fs = require('fs');
var https = require('https');
var mysql = require('mysql');

var options = {
    key: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/privkey.pem'),
    cert: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/cert.pem'),
    ca: fs.readFileSync('/etc/letsencrypt/live/my-domain.de/chain.pem')
};

var serverPort = 8443;
var server = https.createServer(options, app);
var io = require('socket.io')(server); // HERE TO PUT THE DAMN SOCKET.IO!!

server.listen(serverPort, function(){
    console.log('listening on *:' + serverPort);
});


io.on('connection', function(socket){
    console.log('a user connected');

});