node.js 无法获取 /socket.io/?EIO=3&transport=polling&t=LdmmKYz
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41943929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot GET /socket.io/?EIO=3&transport=polling&t=LdmmKYz
提问by noam aghai
I have a problem with my node.js server and my ionic 2 with socket.io (websocket) communication.
我的 node.js 服务器和我的 ionic 2 与 socket.io (websocket) 通信有问题。
My ionic app sends this error:
我的离子应用程序发送此错误:
Cannot GET /socket.io/?EIO=3&transport=polling&t=LdmmKYz
and this is my code, I didn't find my mistake.
这是我的代码,我没有发现我的错误。
my node.js code (using express):
我的 node.js 代码(使用 express):
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use( (req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:8100"); //The ionic server
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var port = Number(process.env.PORT || 8810);
io.on('connection', function (socket) {
console.log('ping-pong started');
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
and this is the ionic 2 app code (inside the constructor):
这是 ionic 2 应用程序代码(在构造函数中):
this.connect = () => {
this.socket = io('http://localhost:8810');
console.log('socket started');
this.socket.emit('connect', {data: 'data'});
this.socket.on('news', (data)=>{
console.log(data);
this.socket.emit('my other event', { my: 'data' });
});
}
this.connect();
What am I missing?
我错过了什么?
回答by noam aghai
I found my problem !
我发现了我的问题!
my problem was at the server code :
我的问题出在服务器代码上:
var server = app.listen(8810)
var io = require('socket.io').listen(server);
just this was the problem.
这就是问题所在。
I needed to define where the socket.io listen without it the socket failed .
我需要定义 socket.io 在没有它的情况下监听套接字失败。
change it and the error will disappeared.
改变它,错误就会消失。
回答by Ananda
Try this in the exact order if you are using express 4.
如果您使用 express 4,请按照确切的顺序尝试此操作。
var express = require('express');
var app = express();
var server = app.listen(8810);
var io = require('socket.io').listen(server);
Refer to the API reference here http://expressjs.com/en/4x/api.html
请参阅此处的 API 参考http://expressjs.com/en/4x/api.html

