Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to construct 'WebSocket': The URL '[object Object]' is invalid

I was trying to make a connection to the websocket and get the data in react router. The connection is not happening and getting error Uncaught SyntaxError: Failed to construct 'WebSocket': The URL '[object Object]' is invalid. in the browser console. Using npm start from the terminal to start the application. It is a simple react router application. Below is the react code where I think problem occurred.

import React from 'react'

export default React.createClass({
  getInitialState: function() {
     return { value : [],
                  client : '' };
  },

   componentWillMount: function() {
      client = new WebSocket("ws://localhost:8000/","echo-protocol");
      client.onerror = function() {
           console.log('Connection Error');
       };

        client.onopen = function() {
          function sendNumber() {
               if (client.readyState === client.OPEN) {
                   var number = Math.round(Math.random() * 0xFFFFFF);
                   client.send(number.toString());
                   setTimeout(sendNumber, 1000);
               }
           }
           sendNumber();
       };

    client.onmessage = function(e) {
            this.setState({
                value: e.data
            });
        }.bind(this);
    },

    componentWillUnmount: function(){
        client.close();
    },

    render: function() {
        return (React.createElement("div",null,this.state.value))
    }
 });

The webpack config file is -

module.exports = {
  entry: './index.js',

  output: {
    filename: 'bundle.js',
    publicPath: ''
  },

  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' }
    ]
  }
}

Also, the packge.json file is

{
  "name": "react_form",
  "version": "1.0.0",
  "description": "Sample form that uses React for its rendering",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --inline --content-base . --history-api-fallback"
  },
  "author": "J",
  "license": "ISC",
  "dependencies": {
    "react": "^0.14.7",
    "react-dom": "^0.14.7",
    "react-router": "^2.0.0",
    "websocket": "^1.0.23"
  },
  "devDependencies": {
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "http-server": "^0.8.5",
    "webpack": "^1.12.13",
    "webpack-dev-server": "^1.14.1"
  }
}

If any other piece of code is required then please let me know. Also, please find the image of the error coming in the console on selecting the route option. Image What is the exact issue I am not able to get ?

like image 438
Worker Avatar asked Oct 30 '22 23:10

Worker


1 Answers

Try this syntax:

const client = new WebSocket("ws://localhost:8000/");
like image 79
Amrit Avatar answered Nov 09 '22 09:11

Amrit