Le Moi
Le Moi

Reputation: 1025

window.WebSocket - window is not defined

I am a bit out of my comfort zone here, so looking for a bit of guidance. I am trying to access an api to display live metrics, using phonic-elixir (https://www.npmjs.com/package/phoenix-elixir) - am just sort of trying to get it running first, so have loaded up their example code and connecting to an api (forgive me if the terminology is all wrong, I am new at this!)

This is my code:

import {Socket} from 'phoenix-elixir';

let socket = new Socket('ws://API_URL_HERE', {params: {'auth-token': 'AUTH_TOKEN'}})

socket.connect()

let channel = socket.channel('updates:new', {})
channel.join()
  .receive('ok', resp => { console.log('Joined successfully', resp) })
  .receive('error', resp => { console.log('Unable to join', resp) })

channel.on('update', payload => {
  console.log('Received: ' + payload);
  console.log(payload);
})

export default socket

When I run babel index.js | node I am getting the error: this.transport = opts.transport || window.WebSocket || LongPoll; and ReferenceError: window is not defined

Just some advice to point me in the right direction would be fantastic. Is window not defined because it needs a dom? Do I need a server to run this in?

Thank you :)

Upvotes: 0

Views: 1233

Answers (2)

Mario Campa
Mario Campa

Reputation: 4252

I just ported the client to be compatible with node.JS.

Here is the link https://github.com/mcampa/phoenix-channels

The difference with the original client is that this does not use long-polling and you need to pass the absolute url instead of the relative url.

To install it run:

npm install --save phoenix-channels

Same API as the original:

const { Socket } = require('phoenix-channels')

let socket = new Socket("ws://example.com/socket")

socket.connect()

// Now that you are connected, you can join channels with a topic:
let channel = socket.channel("room:lobby", {})
channel.join()
  .receive("ok", resp => { console.log("Joined successfully", resp) })
  .receive("error", resp => { console.log("Unable to join", resp) })

Upvotes: 1

Stubb0rn
Stubb0rn

Reputation: 1402

phoenix-elixir is client-side library that is supposed to be used in browsers not in node environment. You should create html page with your code and open it in browser to test it out.

Upvotes: 0

Related Questions