Connecting external app(no phoenix and other ip) to phoenix server using websocket

Hello guys…I am trying to connect a site created in nuxt using port 3000 with my phoenix app using port 4000 through websocket, first I downloaded the Phoenix package in my project

https://www.npmjs.com/package/phoenix
yarn add phoenix

according to this article the WS url seems to be ws://localhost:4000/socket/websocket although I use ws://localhost:4000/socket/ ws://localhost:4000/websocket and ws://localhost:4000/ without luck too

my code is like this

import { Socket } from "phoenix";
var ROOT_SOCKET = 'ws://localhost:4000/socket/websocket';
var socket = new Socket(ROOT_SOCKET);
var chan = socket.channel("connect:2345");
chan.join()
chan.push("ping")

I don’t get notification in my server about connection nor ping request and if I print chan.state I get “errored”

I installed a CORS plug in my phoenix server thinking that probably would be some restriction about the ip’s…but seems not works, I put before my socket channel

  plug CORSPlug
  socket "/socket", ProjectWeb.UserSocket

I’m missing something??? I’m not sure if would be a missconfiguration with CORS, or maybe the address, I’ve tried several ways but not works…also does not generate any error or warning, I’m a bit lost here…

NOTE: if I open the phoenix page localhost:4000 and the chrome dev console, I can connect to the websocket and works ok, so my phoenix server is running well…

any help is appreciate, thank you guys!

1 Like

I also set check_origin to false according to the doc

   transport :websocket, Phoenix.Transports.WebSocket, check_origin: false

https://hexdocs.pm/phoenix/Phoenix.Transports.WebSocket.html

but it still doesnt works :frowning: .

1 Like

Seems you forgot to call socket.connect() before joining channels
Should be something like:

import { Socket } from "phoenix";
var ROOT_SOCKET = 'ws://localhost:4000/socket'; // default path is /socket
var socket = new Socket(ROOT_SOCKET);
socket.connect(); // connect
var chan = socket.channel("connect:2345");
chan.join()
chan.push("ping")

Without the connect call the socket never hits the webserver, thus nothing appears there, also when queried the state of channel you get errored because there was no connection open.

Here is the documentation for Phoenix.js

Hope this helps :smile:

3 Likes

oh man, what a noob mistake!!!..thank you so much, when I was testing the api in the chrome console I included this line but this was missing in my vuejs app, thank you joao!!

2 Likes