无法构建“WebSocket”:URL“[object Object]”无效

IT技术 reactjs npm webpack browserify react-router
2021-05-24 20:30:55

我试图连接到 websocket 并在react-router中获取数据。连接未发生并Uncaught SyntaxError: Failed to construct 'WebSocket': The URL '[object Object]' is invalid.在浏览器控制台中出错使用npm start从终端启动应用程序。这是一个简单的react-router应用程序。以下是我认为发生问题的react代码。

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))
    }
 });

webpack 配置文件是 -

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

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

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

此外, package.json 文件是

{
  "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"
  }
}

如果需要任何其他代码,请告诉我。另外,请在选择路由选项时在控制台中找到错误的图像。图片我无法得到的确切问题是什么?

3个回答

试试这个语法:

const client = new WebSocket("ws://localhost:8000/");

我正在以各种不同的方式调试应用程序。然后我发现代码没有问题。在各种文件中进一步将文件名从WebSockettoSocket和路由名称从webSocketto 更改为socket,并且它起作用了。问题在于命名文件并将它们相应地包含在代码中。

在您的后端,如果您没有带有 key = "Sec-WebSocket-Protocol" 的标头和其中一个协议的值,您将始终在 chrome 上收到此错误。就我而言,Firefox 没问题