Search code examples
node.jswebsocketsocket.ioaccess-control

socket.io / node.js with ssl and Access-Control-Header


I set up a node-server and get an error message when activating ssl (official, NOT self-assigned Certificate).

The error message:

XMLHttpRequest cannot load https://servername:8081/socket.io/... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://servername' is therefore not allowed access. results:1

But actually, I included the following code in my .htaccess file:

<IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin *
  Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
</IfModule>

The apache header module is installed.

my server:

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

var options = {
    key: fs.readFileSync('path to key'),
    cert: fs.readFileSync('path to cert'),
    ca: fs.readFileSync('path to ca')
};

app = express()
https.createServer(options,app).listen(8081)
var io = require('socket.io')(https);

io.sockets.on('connection', function (socket) {
...
}

my client:

<script language="JavaScript">
    var socket = io.connect('https://servername:8081');
    socket.emit(...);
</script>

Does anybody have an idea what is wrong here? Thanks in advance!


Solution

  • Ok, I see a few things here:

    • You need to include the socket.io lib in your client like so:

      <script src="https://servername:8081/socket.io/socket.io.js"></script>
      
    • Set secure parameter to true (in your client)

      var socket = io.connect('https ://servername:8081', {secure: true});
      
    • And add these lines to your SSL options :

      agent: false, 
      requestCert: true,
      rejectUnauthorized: false
      
    • Then if it still doesn't work you can try setting up your server using :

      io.set('match origin protocol', true);