在nodejs上添加socket.io

时间:2016-09-25 17:13:05

标签: javascript node.js socket.io

我正在使用nodejs测试socket.io。

这就是我服务器端的内容:

var app = express();
app.set('port', process.env.PORT || 3000);

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization");
    next();
});
app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});

var http = require('http').Server(app);
var io = require('socket.io')(http);


io.on('connection', function(socket){
    console.log('a user connected');
});

这就是我在客户方面所拥有的:

var socket = io("http://localhost:3000");

我得到了404:

socket.io-1.4.5.js:1 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=LTYKOs3
XMLHttpRequest cannot load http://localhost:3000/socket.io/?EIO=3&transport=polling&t=LTYKOs3. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

我一直在论坛上寻找有关原点的答案并向标题添加信息,但似乎没有任何效果。

任何帮助PLZ? 感谢

1 个答案:

答案 0 :(得分:0)

更改以下代码行:

app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});

var http = require('http').Server(app);
var io = require('socket.io')(http);

到此:

var server = app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});

var io = require('socket.io')(server);

您的代码正在创建第二个服务器,该服务器不在端口3000上并将socket.io绑定到另一个服务器,所以当您尝试在端口3000上使用socket.io时,它没有连接到服务器有socket.io就可以了。我的代码建议将socket.io绑定到端口3000上的一个快速服务器,并且不创建第二个服务器。