C
C
codeZlo2019-02-06 20:19:20
Node.js
codeZlo, 2019-02-06 20:19:20

How to properly install SSL certificate with Node.js script (Socket.io)?

Installed free SSL from reg.ru on a node.js script as follows (back):

var https = require('https')
var options = {
    key:    fs.readFileSync('1.pem').toString(),
    cert:   fs.readFileSync('2.pem').toString()
}
var app = https.createServer(options)
var io = require('socket.io').listen(app) 
app.listen(config.port || 8083)

front:
var socketIO = io('https://domain.com:8080' || 'https://domain.com:8083', {secure: true})
socketIO.once('connect', function(){
})

On Mac OS in Chrome, everything works fine, it connects. On Windows in Chrome, an infinite error:
socket.io-1.4.5.js:1 GET https://domain.com:8080/socket.io/?EIO=3&transport=polling&t=MZ3p6fg net::ERR_SSL_PROTOCOL_ERROR socket.io-1.4.5.js:1

Guys, help, please, the whole brain is broken. What could be the problem?
1.pem - -----BEGIN RSA PRIVATE KEY-----
2.pem - -----BEGIN CERTIFICATE-----

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
Boris Korobkov, 2019-02-07
@BorisKorobkov

Possibly a crooked certificate. Provide a link to your site.
Try a different certificate. For example, letsencrypt

D
de1m, 2019-02-07
@de1m

From my old answer.
It will not work on one port, two ports are needed.
I changed the example, but this one definitely works for me, on only two ports

var express = require('express');  
var app = express();  
var server = require('http').createServer(app);  
var io = require('socket.io')(server);
var fs = require('fs');
var https = require('https');

app.set('views', __dirname + '/views')
app.set('view engine', 'pug')
app.use(express.static(__dirname + '/public'))

server.listen(5000, function () {
  console.log('Server listening at port %d', 5000);
});

const opts = {
  key: fs.readFileSync('privateKey.key'),
  cert: fs.readFileSync('certificate.crt')
}

var httpsServer = https.createServer(opts, app);
httpsServer.listen(5001, function(){
  console.log("HTTPS on port " + 5001);
})

app.get('/', function (req, res) {
  res.render('index');
})

io.attach(httpsServer);
io.attach(server);

io.on('connection', function(client) {  
    console.log('Client connected...');
    client.on('click', function(data){
      console.log(JSON.parse(data));
        setTimeout(function() {
          client.emit("ok", "data");
        }, 3000);
    })
});

On the client side, you need to add an http or https check.
if (window.location.protocol != "https:"){
        var socket = io.connect('https://localhost:5001');    
    } else {
        var socket = io.connect('http://localhost:5000');
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question