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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With