简体   繁体   中英

Socket.io (NodeJS) allow CORS

I am building a python (django) app with some real time functionality provided by node using socket.io. Django app is running on http://127.0.0.1:8001 and the socket.io server on http://127.0.0.1:8002 . Problem is in loading socket.io like this on the django template:

<script src="http://localhost:8002/socket.io/socket.io.js"></script>

I have tried to allow CORS on my node script using 'origins' but nothing works still. Here is my code:

var http = require('http');
var server = http.createServer().listen(8002);
var io = require('socket.io').listen(server);
var cookie_reader = require('cookie');
var querystring = require('querystring');
var redis = require('redis');

//Configure socket.io to store cookie set by Django
io.use(function(){
    io.set('authorization', function(data, accept){
        if(data.headers.cookie){
            data.cookie = cookie_reader.parse(data.headers.cookie);
            return accept(null, true);
        }
        return accept('error', false);
    });
    io.set('log level', 1);
    io.set('origins', 'http://127.0.0.1:8001');
});

io.sockets.on('connection', function (socket) {
    // Create redis client
    client = redis.createClient();

    // Subscribe to the Redis events channel
    client.subscribe('notifications.' + socket.handshake.cookie['sessionid']);

    // Grab message from Redis and send to client
    client.on('message', function(channel, message){
        console.log('on message', message);
        socket.send(message);
    });

    // Unsubscribe after a disconnect event
    socket.on('disconnect', function () {
        client.unsubscribe('notifications.' + socket.handshake.cookie['sessionid']);
    });
});

Error I get on chrome:

XMLHttpRequest cannot load http://localhost/socket.io/?EIO=3&transport=polling&t=1433331728612-1086. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8001' is therefore not allowed access. The response had HTTP status code 404.

In my HTML I had this:

var socket = io.connect("localhost", {port: 8002});

Changing it to var socket = io.connect("127.0.0.1:8002"); solved the CORS 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