【问题标题】:Could not connect websocket using Action Cable无法使用 Action Cable 连接 websocket
【发布时间】:2018-03-10 23:22:54
【问题描述】:

在 Rails 5.1 中无法使用 Action Cable 连接 websocket。 HTTP 服务器是 nginx 上的 Unicorn,适配器是 Redis。

Rails 配置如下。

# config/environments/production.rb
config.action_cable.disable_request_forgery_protection = true

nginx配置如下。

upstream unicorn {
  server unix:/rails/current/tmp/sockets/unicorn.sock;
}

server {
  listen 80;
  charset utf-8;
  server_name sub.example.com;
  root /rails/current/public;

  location / {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    if (!-f $request_filename) {
      proxy_pass http://unicorn;
      break;
    }
  }
  location /cable {
    proxy_pass http://unicorn;
    proxy_http_version 1.1;
    proxy_set_header Upgrade "websocket";
    proxy_set_header Connection "Upgrade";
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
    proxy_redirect off;
  }
  ...
}

浏览器控制台报错如下。

WebSocket connection to 'wss://sub.example.com/cable' failed: Error during WebSocket handshake: Unexpected response code: 404

Rails 中的错误如下。

[ERROR] Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: close, HTTP_UPGRADE: )
[INFO] Finished "/cable/"[non-WebSocket] for xxx.xxx.xxx.xxx at 2017-xx-xx

最奇怪的是 Rails 中的错误没有HTTP_UPGRADE。但是网页浏览器的HTTP请求头包含Upgrade键和websocket值。还在 nginx 配置中为代理标头设置 "websocket"

我该怎么办?

【问题讨论】:

    标签: ruby-on-rails nginx websocket actioncable


    【解决方案1】:

    在那篇文章的背面,我刚刚意识到通用解决方案是 对 config/secrets.yml 文件进行简单更改以引用 ENV["PORT"] 设置 ...

    # Be sure to restart your server when you modify this file.

    development:
      secret_key_base: 231bf79489c63f8c8facd7...
      action_cable_url : http://localhost:<%= ENV["PORT"] %>
    
    test:
      secret_key_base: 1ab8adbcf8410aebb...
      action_cable_url : http://localhost:<%= ENV["PORT"] %>
    
    # Do not keep production secrets in the repository,
    # instead read values from the environment.
    production:
      secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
      action_cable_url : <%= ENV["SERVER_PORT"] %>
    

    你也可以在你的点文件中包含这个:

    导出端口=3000

    source

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多