无法构造'WebSocket':URL'[object Object]'无效 [英] Failed to construct 'WebSocket': The URL '[object Object]' is invalid
问题描述
我试图建立与Websocket的连接,并在React Router中获取数据。未建立连接,并出现错误未捕获的语法错误:无法构造 WebSocket:URL [object Object]无效。
在浏览器控制台中。在终端上使用 npm start
启动应用程序。这是一个简单的反应路由器应用程序。以下是我认为发生问题的代码。
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))
}
});
Webpack配置文件为-
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' }
]
}
}
此外,packge.json文件是
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. What is the exact issue I am not able to get ?
推荐答案
尝试以下语法:
const client = new WebSocket("ws://localhost:8000/");
这篇关于无法构造'WebSocket':URL'[object Object]'无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!