简体   繁体   中英

Cannot GET /socket.io/?EIO=3&transport=polling&t=LdmmKYz

I have a problem with my node.js server and my ionic 2 with socket.io (websocket) communication.

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):

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):

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?

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 .

change it and the error will disappeared.

Try this in the exact order if you are using 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

When I tried your solution I received an error: Error [ERR_SERVER_ALREADY_LISTEN]: Listen method has been called more than once without closing. What is the problem?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM