在Socket.io.js

时间:2018-05-28 17:43:09

标签: node.js apache ssl socket.io

我刚刚从GoDaddy获得了ssl证书,我现在在https://example.com中运行该网站,在http://example.com:3000中运行我的socketio服务器(它无法访问https中的socketio)

这是我从控制台获取的错误消息

"来源“https://example.com:3000/socket.io/socket.io.js

的加载失败

这就是我添加socket.io.js

的方法
<script src="<?php print BASE_URL; ?>:3000/socket.io/socket.io.js"></script>

这是我的nodejs服务器,带有socket.io

var app = require('express')();
var cors = require('cors');
var https = require('https').Server(app);
var io = require('socket.io')(https);
var _ = require('lodash');

// more include files here ...

https.listen(3000, function() {
  utils.logger('Listening on *: 3000', 'info');
});

io.use(function(socket, next) {
  let found = _.findIndex(socketStore.connections, { 'userId': socket.request._query.userId });

if (parseInt(socket.request._query.userId) !== 0) {
  if (found < 0) {
    socketStore.connections.push({
      userId: parseInt(socket.request._query.userId),
      socket: socket
    });
  }
  else {
    socketStore.connections[found] = {
      userId: parseInt(socket.request._query.userId),
      socket: socket
    };
  }

  utils.logger(`User connected from ${socket.request.connection.remoteAddress}`, 'info');
  utils.logger(`User ${socket.request._query.userId} is now online!`, 'info');

    next();
  }
});

// Socket IO
io.on('connection', function(socket) {
    // some stuffs
});

app.use(cors({ origin: '*' }));

// Routes and Endpoints
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

这是我的默认apache ssl config

<IfModule mod_ssl.c>
  <VirtualHost _default_:443>
    ServerAdmin webmaster@example.com
    ServerName example.com

    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    SSLEngine on

    SSLCertificateFile /root/ssl/example.com.crt
    SSLCertificateKeyFile /root/ssl/example.com.key

    <FilesMatch "\.(cgi|shtml|phtml|php)$">
      SSLOptions +StdEnvVars
    </FilesMatch>
    <Directory /usr/lib/cgi-bin>
      SSLOptions +StdEnvVars
    </Directory>
    <Directory "/var/www/html">
      Options Indexes FollowSymLinks MultiViews
      AllowOverride All
      Order allow,deny
      Allow from all
    </Directory>

  </VirtualHost>
</IfModule>

1 个答案:

答案 0 :(得分:0)

您的错误消息:

&#34;来源“https://example.com:3000/socket.io/socket.io.js

的加载失败

正在尝试从/socket.io/socket.io.js服务器加载HTTPS,但您显示的代码是使用HTTP而不是HTTPS的socket.io服务器。您没有向我们展示这个来自的网页,但是用于加载socket.io.js库的<script>标记需要与您的socket.io服务器正在侦听的协议相同。 / p>

如果您已经有https服务器,那么您也应该将它用于socket.io。没有必要为socket.io创建单独的http服务器,事实上,从http页面访问https资源是一种不好的做法,因为它会欺骗/欺骗用户关于页面的安全性。