2017-09-29 81 views
0

無法使用Rails 5.1中的動作電纜連接WebSocket。 HTTP服務器是nginx上的Unicorn,適配器是Redis。無法使用動作電纜連接WebSocket

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"

我該怎麼辦?

回答

0

在該書面記錄後,我才意識到通用的解決方案是 一個簡單的改變到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"] %> 

您還可以在這個點的文件:

出口PORT = 3000

source

相關問題