Socket.io works only on localhost

Posted 3 years ago by zabi.zamir

I am trying to implement sockets by following the tutorial https://laracasts.com/discuss/channels/general-discussion/step-by-step-guide-to-installing-socketio-and-broadcasting-events-with-laravel-51 . I got node.js running, reddis working and port 3000 is listening. I can get console messages on command line. Problem occurs when i try to emit anything to the client side. Sever side:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('test-channel', function(err, count) {
});
redis.on('message', function(channel, message) {
    console.log('Message Recieved: ' + message);
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
    console.log('Listening on Port 3000');
});

Client side:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js"></script>
<script>
       /var socket = io('http://serverip:3000');
    socket.on("test-channel:App\\Events\\EventName", function(message){
        console.log("Working");
        // increase the power everytime we load test route
        $('#power').text(parseInt($('#power').text()) + parseInt(message.data.power));
    });

It works perfectly fine on locahost, but from external ip it gives me Access-Control-Allow-Origin 502 Error.

GET http://serverip:3000/socket.io/?EIO=3&transport=polling&t=LDrVJCA Request.create @ socket.io.min.js:1Request @ socket.io.min.js:1XHR.request @ socket.io.min.js:1XHR.doPoll @ socket.io.min.js:1Polling.poll @ socket.io.min.js:1Polling.doOpen @ socket.io.min.js:1Transport.open @ socket.io.min.js:1Socket.open @ socket.io.min.js:1Socket @ socket.io.min.js:1Socket @ socket.io.min.js:1Manager.open.Manager.connect @ socket.io.min.js:2(anonymous function) @ socket.io.min.js:3
feedTest:1 XMLHttpRequest cannot load http://serverip:3000/socket.io/?EIO=3&transport=polling&t=LDrVJCA. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access. The response had HTTP status code 502.

I also changed cdn socket.io.min.js and stored locally as few people suggested that. I have been trying every single suggestion and example available online but nothing helped. Any help would be much appreciated. Thanks

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.