javascript – Socket.io PhoneGap

当我尝试使用Socket.io与PhoneGap我得到这个错误:

(在iOS上应该支持socket.io)

Origin null is not allowed by Access-Control-Allow-Origin.

这是因为我的应用程序是通过file://协议提供的。我能做些什么来解决这个问题?

谢谢!!

您必须将socketio主机添加到PhoneGap.plist中的“ExternalHosts”键。

Faq

Q. Links to and imported files from external hosts don’t load?

A. The latest code has the new white-list feature. If you are referencing external hosts,
you will have to add the host in PhoneGap.plist under the “ExternalHosts” key. Wildcards are ok.
So if you are connecting to “07001”, you have to add “phonegap.com” to the list (or use the wildcard “*.phonegap.com”
which will match subdomains as well). (Note: If you open the plist
file in Xcode, you won’t need to fiddle with the XML syntax.)

对于android,您必须编辑cordova.xml并添加对socketio主机的访问权限:

<access origin="HOST*"/> 

index.html(带socketio示例):

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

app.js(服务器端javascript /基本socketio示例):

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {

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

HOST您必须替换为您的socket.io服务器的主机名!

翻译自:https://stackoverflow.com/questions/10738073/socket-io-phonegap

转载注明原文:javascript – Socket.io PhoneGap