通过HTTPS使用nodejs的Faye

时间:2015-07-12 12:41:30

标签: ruby-on-rails node.js faye

我正在尝试设置我的生产服务器以使用nodejs和HTTPS来使用faye消息,但没有运气。

到目前为止我所拥有的是:

faye + nodejs服务器设置文件:

var https = require('https');
var faye = require('faye');
var fs = require('fs');

var options = {
    key: fs.readFileSync('/etc/httpd/ssl/example.com.key'),
    cert: fs.readFileSync('/etc/httpd/ssl/example.com.crt'),
    ca: fs.readFileSync('/etc/httpd/ssl/ca_bundle.crt')
};

var server = https.createServer(options);
var bayeux = new faye.NodeAdapter({mount: '/faye', timeout: 60});

bayeux.attach(server);
server.listen(8000);

用于发送消息的rails助手:

def broadcast(channel, &block)
  message = {:channel => channel, :data => capture(&block)}
  uri = URI.parse(Rails.configuration.faye_url)
  Net::HTTPS.post(uri, message.to_json)
end

用于打开侦听器的javascript函数:

function openListener(channel, callback){
    var faye_client = new Faye.Client("<%= Rails.configuration.faye_url %>");
    faye_client.subscribe(channel , callback);
    return faye_client;
}

my faye url config in production.rb:

config.faye_url = "https://example.com:8000/faye"

最后,在我的页面中调用javascript:

fayeClient = openListener("my_channel" , function(data) {
    //do something...
});

在开发机器上测试http时,一切正常。但在生产中没有。

如果我将浏览器指向https://example.com:8000/faye.js,我会收到正确的javascript文件。

可能会发生什么?

1 个答案:

答案 0 :(得分:3)

问题在于Apache服务器。

我已切换到nginx,现在正在使用。

但是,我需要进行一些配置:

Faye + node.js设置文件:

var http = require('http'),
    faye = require('faye');

var server = http.createServer(),
    bayeux = new faye.NodeAdapter({mount: '/faye', timeout: 60});

bayeux.attach(server);
server.listen(8000);

Rails帮助:

def broadcast(channel, &block)
  message = {:channel => channel, :data => capture(&block)}
  uri = URI.parse(Rails.configuration.faye_url)
  Net::HTTP.post_form(uri, :message => message.to_json)
end

Faye url:

https://example.com/faye

最后,nginx config

server {
    # Listen on 80 and 443
    listen 80;
    listen 443 ssl;
    server_name  example.com;
    passenger_enabled on;
    root /home/rails/myapp/public;

    ssl_certificate /home/rails/ssl/myapp.crt;
    ssl_certificate_key /home/rails/ssl/myapp.key;

    # Redirect all non-SSL traffic to SSL.
    if ($ssl_protocol = "") {
            rewrite ^ https://$host$request_uri? permanent;
    }

    location /faye {
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

简短的字:nginx将/ faye地址中的https请求转换为端口8000中的http。 在服务器端使用默认http,在客户端使用https。