【问题标题】:Socket.io (NodeJS) allow CORSSocket.io (NodeJS) 允许 CORS
【发布时间】:2015-06-03 20:59:38
【问题描述】:

我正在构建一个 python (django) 应用程序,该应用程序具有节点使用 socket.io 提供的一些实时功能。 Django 应用在http://127.0.0.1:8001 上运行,socket.io 服务器在http://127.0.0.1:8002 上运行。问题在于在 django 模板上像这样加载 socket.io:

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

我尝试使用“origins”在我的节点脚本上允许 CORS,但仍然没有任何效果。这是我的代码:

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']);
    });
});

我在 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.

【问题讨论】:

  • 实际问题是什么?您的 Node 代码看起来不完整(server 是什么?),并且 Socket.io 应该能够在没有 CORS 的情况下工作(但是,CSP 可能仍然是一个问题)。
  • @robertklep 我已经用所有信息编辑了我的问题
  • 看起来您的客户端正在连接到端口 80 而不是 Socket.IO 服务器的端口 8002。您还在使用旧版本的 Socket.IO(1.0 之前),尽管这应该不是问题。

标签: django node.js sockets socket.io


【解决方案1】:

在我的 HTML 中,我有这个:

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

将其更改为 var socket = io.connect("127.0.0.1:8002"); 解决了 CORS 问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-17
    • 2023-03-30
    • 2021-05-09
    • 2021-01-21
    • 2015-07-20
    • 2020-06-29
    • 2021-01-09
    • 2021-11-23
    相关资源
    最近更新 更多