NodeJs express.io跨源请求被阻止



我是nodejs和express.io的新手,我试图使用express.io样本来测试广播,但我遇到了这个错误,无法修复

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://file/socket.io/?EIO=3&transport=polling&t=1424977776399-0. This can be fixed by moving the resource to the same domain or enabling CORS.

示例代码:

app = require('express.io')()
app.http().io()
// Broadcast the new visitor event on ready route.
app.io.route('ready', function(req) {
    req.io.broadcast('new visitor')
})
// Send client html.
app.get('/', function(req, res) {
    res.sendfile(__dirname + '/client.html')
})
app.listen(7076) 

HTML:

<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
<script src="socket.io.js"></script>
<script>
io = io.connect()
// Send the ready event.
io.emit('ready')
// Listen for the new visitor event.
io.on('new visitor', function() {
    $('body').append('<p>New visitor, hooray! ' + new Date().toString() +'</p>')
})
</script>

您遇到了CORS问题。给定从域a加载的页面,出于安全原因,未经域B同意,您不能向域B请求。请参阅http://acuriousanimal.com/blog/2011/01/27/working-with-the-javascript-xmlhttprequest-object/以便更好地解释。

我从未使用过express.io框架,但它可能是基于XMLHttpRequest进行请求调用的。

必须启用cors模块(请参阅https://github.com/techpines/express.io/issues/117)或者,将Access-Control-Allow-*附加到服务器的响应。

最新更新