简体   繁体   English

Https Nginx NodeJS SocketIO和CORS请求失败

[英]Https Nginx NodeJS SocketIO And CORS request failed

Here is my problem, 这是我的问题,

Context : 背景:

I have a NGinx server working. 我有一台NGinx服务器正在运行。 NGinx uses a certificate to enable HTTPS. NGinx使用证书启用HTTPS。 No problem from there. 没问题。

I have a NodeJS server working, which is just supposed to handle websockets, using socketIO. 我有一个NodeJS服务器工作,它应该使用socketIO来处理websockets。

I am testing on Mozilla Firefox (which is maybe not the best thing...) 我正在测试Mozilla Firefox(这可能不是最好的......)

App was first on HTTP, and everything was working fine. 应用程序首先在HTTP上,一切正常。 Now that all switched to HTTPS, I face a "cross-origin" issue. 现在所有人都切换到了HTTPS,我面临着一个“跨领域”的问题。

I already tried several solutions, but none of them worked for me yet... I will explain what I tried at the end of the post. 我已经尝试了几种解决方案,但它们都没有为我工作......我会解释我在帖子末尾尝试的内容。

First, let me show you the concerned files, server.js for nodeJS, nginx.conf for NGinx server, and "client script" which is supposed to connect the websocket. 首先,让我向您展示有关的文件,nodeJS的server.js,NGinx服务器的nginx.conf,以及应该连接websocket的“客户端脚本”。

server.js - NodeJS server.js - NodeJS

var app = require('express')();
var fs = require('fs');
var https = require('https');
var _ = require('underscore');
var socketio = require('socket.io');
var options = {
    key: fs.readFileSync('/ssl/file.key'),
    cert: fs.readFileSync('/ssl/file.crt')
};
var server = https.createServer(options).listen(9001,function(){
    console.log("SERVER LISTENING");
});
io = socketio.listen(server,{origins:'*:*'});

var connectedSockets = {};

_.each(io.nsps, function(nsp){
  nsp.on('connect', function(socket){
    if (!socket.auth) {
      delete nsp.connected[socket.id];
    }
  });
});

function checkAuthToken(token,callback){
    callback(null,true);
}

io.on('connection',function(socket){
    socket.broadcast.emit('hi');
    socket.on('disconnect',function(){
        console.log('a user disconnected');
    });
    socket.on('chat message',function(msg){
        io.emit('chat message',msg);
    });
    socket.on('authenticate', function(data){
      checkAuthToken(data.token, function(err, success){
        if (!err && success){
          socket.auth = true;
          _.each(io.nsps, function(nsp) {
            if(_.findWhere(nsp.sockets, {id: socket.id})) {
              nsp.connected[socket.id] = socket;
            }
          });
        }
      });
    });
});

It is a "simple" chat application, several things need to be completed such as the script that is supposed to check authentification... 这是一个“简单”的聊天应用程序,需要完成几件事情,例如应该检查身份验证的脚本......

nginx.conf - NGinx Server Config nginx.conf - NGinx服务器配置

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    map $http_upgrade $connection_upgragde {
        default upgrade;
        '' close;
    }
    sendfile        on;
    server {
        listen 80;
        server_name 192.168.100.22;
        rewrite ^ https://$http_host$request_uri? permanent;
    }
    server {
        listen       443;
        ssl on;
        ssl_certificate /ssl/file.crt;
        ssl_certificate_key /ssl/file.key;
        server_name  192.168.100.22;
        root E:/www;
        index index.php index.html index.htm;
        add_header Access-Control-Allow-Origin *;
        add_header Strict-Transport-Security "max-age=31536000; includeSubdomains";
        proxy_set_header X-Forwarded-For $remote_addr;
        server_tokens off;
        charset utf-8;
        error_page   500 502 503 504  /50x.html;
        location ~ \.php$ {
            try_files $uri =404;
            include /Nginx/nginx-1.8.0/conf/fastcgi_params;
            fastcgi_param HTTPS on;
            fastcgi_param HTTP_SCHEME https;
            fastcgi_split_path_info ^(.+\.php)(.*)$;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
    }
}

Client.js - Connection script in index.php Client.js - index.php中的连接脚本

<script src="./jquery-1.11.1.js"></script>
<script src="./socket.io-1.3.5.js"></script>
<script>
  var socket = io('wss://192.168.100.22:9001');
  $("form").submit(function(){
    socket.emit('chat message',$('#m').val());
    $('#m').val('');
    return false;
  });
  socket.on('connect', function(){
      socket.emit('authenticate', {token: 456456456,rights:'any'});
    });
  socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });
  socket.on('hi',function(){
    $('#messages').append($('<li>').text('connection'));
  });
</script>

The server is located on 192.168.100.22 IP 服务器位于192.168.100.22 IP上

Nginx listens 80 & 443 and redirects all traffic to 443 (https) Nginx侦听80和443并将所有流量重定向到443(https)

Access to folders through nginx is ok, the current chat test is located at 192.168.100.22/websocks/index.php 通过nginx访问文件夹是可以的,当前的聊天测试位于192.168.100.22/websocks/index.php

Error message is the following : 错误消息如下:

GET https://192.168.100.22:9001/socket.io/?EIO=3&transport=polling&t=1432131062725-0 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://192.168.100.22:9001/socket.io/?EIO=3&transport=polling&t=1432131062725-0. Reason: CORS request failed

Actually, I already tried to add this to the nodejs script : 实际上,我已经尝试将其添加到nodejs脚本:

https.globalAgent.options.rejectUnauthorized = false;
app.get('*',function(req,res,next){
    res.header("Access-Control-Allow-Origin","*");
    res.header("Access-Control-Allow-Headers","X-Requested-With");
    next();
});

But Nothing worked yet... 但还没有工作......

Thanks for reading / help 感谢您的阅读/帮助

Verify that your SSL certificate is valid and name matches your domain. 验证您的SSL证书是否有效且名称是否与您的域匹配。 It looks like you are using the IP address instead of the domain name of the certificate. 看起来您使用的是IP地址而不是证书的域名。 I've seen the CORS error when Firefox was complaining about the certificate. 当Firefox抱怨证书时,我看到了CORS错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM