Monday, 13 March 2017

Rails 5 - ActionCable - Failed to upgrade to WebSocket

I'm trying to implement a webSocket on a my Rails 5 application.

Here's my channel:

class MessagesChannel < ApplicationCable::Channel
  def subscribed
    stream_from "messages_#{params[:topic]}"
  end
end

In my controller I do:

    ActionCable.server.broadcast "messages_#{params[:topic_id]}",
      message: @message.message,
      user: current_user.name

And my connection class (using Device also):

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.email
    end

    protected

    def find_verified_user # this checks whether a user is authenticated with devise
      if verified_user = env['warden'].user
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

The client is a Nodejs application just to test:

module.exports.webSocket = function(topic){
  const WebSocket = require('ws');

  const ws = new WebSocket('ws://localhost:3000/cable');

  ws.on('open', function open() {
    console.log("on open!!");
  });

  ws.on('message', function incoming(data, flags) {
    console.log("got here!");
    console.log(data);
    console.log(flags);
    // flags.binary will be set if a binary data is received.
    // flags.masked will be set if the data was masked.
  });
};

And this is what I get:

Started GET "/cable" for 127.0.0.1 at 2017-03-13 14:25:01 -0300
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2017-03-13 14:25:01 -0300
Request origin not allowed:
Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2017-03-13 14:25:01 -0300

I also dont know how to specify the channel to listen to on the NodeJS client. This would also be helpful



via Marco Noronha

No comments:

Post a Comment