使用快速js在套接字io上阻止跨源请求

时间:2014-05-12 12:43:39

标签: javascript node.js express socket.io

我正在使用节点js,expressjs,socketio,redis和Django。

节点服务器:

const PORT = 8008;
const HOST = 'localhost';

var express = require('express'),
    http = require('http'),
    server = http.createServer(app);

var app = express();

const redis = require('redis');

log('info', 'connected to redis server');

const io = require('socket.io');

if (!module.parent) {
    server.listen(PORT, HOST);
    const socket = io.listen(server);

    socket.on('connection', function(client) {
        const subscribe = redis.createClient(6379, '127.0.0.1')
        subscribe.subscribe('test');

        subscribe.on("message", function(pattern, channel, message) {
            client.send(channel, message);
            log('msg', "received from channel #" + channel + " : " + message);
        });

    });

客户端:

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

<script type="text/javascript">

var socket = io.connect("http://localhost:8008/");

      socket.on('connect', function(data){
        socket.emit('subscribe', {channel:'test'});
      });


      socket.on('message', function (data) {
        console.log('received a message: ', data);

      });

服务器正在向该频道发送消息,但是当它在客户端上加载时,我收到以下错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8008/socket.io/1/?t=1399898337175. This can be fixed by moving the resource to the same domain or enabling CORS.

2 个答案:

答案 0 :(得分:7)

您还可以配置套接字服务器以启用通配符源。

io.configure('development', function(){
    io.set('origins', '*:*');
}

或者

io.set('origins', '*:*');

检查https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO了解更多

答案 1 :(得分:1)

您必须在服务器端启用cors。

在节点代码中添加它

// Enables CORS
var enableCORS = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');

        // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
        res.send(200);
    } else {
        next();
    };
};

app.configure(function() {
    // enable CORS!
    app.use(enableCORS);

});