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

pyn*_*ice 2 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);
        });

    });
Run Code Online (Sandbox Code Playgroud)

客户:

<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);

      });
Run Code Online (Sandbox Code Playgroud)

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

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.

小智 7

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

io.configure('development', function(){
    io.set('origins', '*:*');
}
Run Code Online (Sandbox Code Playgroud)

要么

io.set('origins', '*:*');
Run Code Online (Sandbox Code Playgroud)

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