2015-02-04 54 views
0

我试图调用正在通过socket.io担任了一个网页,我得到以下错误:socket.io和jQuery负载

XMLHttpRequest cannot load http://foo.bar:12354/ . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://foo.bar ' is therefore not allowed access.

下面是我调用的页面非常简单JQ代码:

$(document).ready(function() { 
    $('#x').load('http://foo.bar:12354'); 
}); 

这里是我的简单socket.io例如:

var app = require('express')(); 
var server = require('http').Server(app); 
var io = require('socket.io')(server); 
server.listen(12354); 
io.on('connection', function (socket) { 
     socket.emit('news', { hello: 'world' }); 
     socket.on('my other event', function (data) { 
       console.log(data); 
     }); 
}); 
app.get('/', function (req, res) { 
     res.sendFile(__dirname + '/index.html'); 
});          
app.use(function(req, res, next) { 
     res.header("Access-Control-Allow-Origin", "http://foo.bar:12354"); 
     res.header("Access-Control-Allow-Headers", "X-Requested-With"); 
     res.header("Access-Control-Allow-Headers", "Content-Type"); 
     res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS"); 
     next(); 
}); 

当我拉起来,直接使用页面页面加载正常。

一个论坛上建议,我需要包括阿帕奇CORS审批,但把这个变成一个点接入没有帮助:

Header set Access-Control-Allow-Origin "*" 

这似乎是它应该是一个相当简单的任务,但它有我难住了。任何建议都会让人感激。

+0

尝试将“Access-Control-Allow-Origin”添加到您的快速app.use:'res.header(“Access-Control-Allow-Origin”,“*”);' – pherris

+0

谢谢pherris - 那是我尝试的第一件事。我还在res.header之前放置了一个console.log行。当我使用h t t p:// foo时,这条线会发射。酒吧/网址,但是当我使用jQ加载它根本不会启动。这应该是对我很重要的线索,但我仍然没有看到它。 – edwardsmarkf

+0

这是什么代码,index.html? '$(document).ready(function(){('#x').load('http://foo.bar:12354'); });' – pherris

回答

0

在这个例子中,express服务于你的静态内容,所以你不需要用jQuery的load()方法来获取你的页面 - 你的内容就是任何HTML/JS/CSS在index.html文件中建立websocket连接到刚刚服务的服务器)。

它看起来从the docs表示和socket.io可以使用相同的端口(不需要交叉起源的东西)。所以,我建议切换到端口80,按照该如何向一区,但没有了jQuery负载()的示例片:

var app = require('express').createServer(); 
var io = require('socket.io')(app); 

app.listen(80); 

app.get('/', function (req, res) { 
    res.sendfile(__dirname + '/index.html'); 
}); 

io.on('connection', function (socket) { 
    socket.emit('news', { hello: 'world' }); 
    socket.on('my other event', function (data) { 
    console.log(data); 
    }); 
}); 

的index.html

<script src="/socket.io/socket.io.js"></script> 
<script> 
    var socket = io.connect('http://localhost'); 
    socket.on('news', function (data) { 
    console.log(data); 
    socket.emit('my other event', { my: 'data' }); 
    }); 
</script> 

那么你应该只能够从浏览器中点击http://foo.bar(端口80)并在浏览器和服务器上查看console.log。我不认为你需要任何交叉源请求,因为套接字连接到服务于静态内容的相同端口。

+0

谢谢你弗里斯 - 我没有让自己完全清楚 - 所以我在这里转载问题:http://stackoverflow.com/questions/28372043/express-io-and-jquery – edwardsmarkf