我试图建立与websocket的连接并在反应路由器中获取数据。连接未发生并在浏览器控制台中收到错误Uncaught SyntaxError: Failed to construct 'WebSocket': The URL '[object Object]' is invalid.
。使用终端中的npm start
启动应用程序。它是一个简单的反应路由器应用程序下面是我认为问题发生的反应代码。
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' }
]
}
}
此外,packge.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"
}
}
答案 0 :(得分:2)
try this syntax
client = new WebSocket(" ws:// localhost:8000 /");
答案 1 :(得分:0)
我正在以各种不同的方式调试应用程序。然后我发现代码没有问题。进一步将文件名称从WebSocket
更改为Socket
,并在各种文件中将名称从webSocket
路由到socket
并且有效。问题在于命名文件并相应地将它们包含在代码中。
答案 2 :(得分:0)
在后端,如果您没有标头为“ Sec-WebSocket-Protocol”且标头之一的标头,则在chrome上始终会出现此错误。 就我而言,使用Firefox很好