11

我在使用这些日志消息连接到非开发环境中的 websocket 时遇到问题

Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: close, HTTP_UPGRADE: )

Finished "/cable/"[non-WebSocket] for 127.0.0.1 at 2016-07-06 09:44:29 +1000

我调试了一下,发现浏览器/javascript发送的请求与unicorn(使用nginx运行)收到的请求不完全相同。

浏览器的请求头是

GET ws://cc-uat.com.au/cable HTTP/1.1
Host: cc-uat.com.au
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://cc-uat.com.au
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cookie: <Lot of cookies>
Sec-WebSocket-Key: QGdJkYIA2u7vtmMVXfHKtQ==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Protocol: actioncable-v1-json, actioncable-unsupported

这里的连接是“升级”,但 websocket 请求的连接是“关闭”的(可能是 nginx 搞砸了?)

而websocket驱动程序中的这段代码失败了

def self.websocket?(env)
      connection = env['HTTP_CONNECTION'] || ''
      upgrade    = env['HTTP_UPGRADE']    || ''

      env['REQUEST_METHOD'] == 'GET' and
      connection.downcase.split(/ *, */).include?('upgrade') and
      upgrade.downcase == 'websocket'
end

更新

这是我的 nginx 配置

upstream app {
    server unix:/home/osboxes/sites/actioncable-examples/shared/sockets/unicorn.sock fail_timeout=0;
}

server {
    listen 80;
    server_name localhost;

    root /home/osboxes/sites/actioncable-example/public;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_pass http://app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "upgrade";
    }


    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}

我已经在 /cable 上安装了 actioncable 服务器

mount ActionCable.server => "/cable"

通过 nginx 更改,我能够成功握手,但服务器无法发送心跳并且连接不断下降。

Started GET "/cable" for 127.0.0.1 at 2016-07-07 05:48:06 +0100
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2016-07-07 05:48:06 +0100
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: upgrade, HTTP_UPGRADE: websocket)
4

3 回答 3

3

您是否config.action_cable.allowed_request_origins在 production.rb 中设置了允许来自您的生产域的连接?在我的 nginx.conf 中也有

proxy_set_header X-Real-IP $remote_addr;  
proxy_set_header X-Forwarded-Proto http;

我不完全确定它们是否真的需要,但它对我有用。

于 2016-07-11T19:21:08.457 回答
0

感谢上面的答案,我得到了类似的错误。问题是我保留后端 url 地址以config.action_cable.allowed_request_origins将其更改为前端 url 问题得到解决。更清楚地说,我在完全不同的域中拥有字体端和后端

于 2020-02-14T15:38:38.653 回答
0

Rails 5 动作电缆 CORS:

创建一个 ruby​​ 文件 ieaction_cable.rbmy_rails_project/config/initializers添加以下代码。

if Rails.env.development?
  Rails.application.config.action_cable.allowed_request_origins =  ['http://localhost:3001', 'http://127.0.0.1:3001']
end

你完成了。

于 2017-06-09T09:53:44.633 回答