当我尝试使用 Socket.IO与 PhoneGap我收到此错误:
(在应该支持 socket.io 的 iOS 上)
Origin null is not allowed by Access-Control-Allow-Origin.
这是因为我的应用是通过 file://
协议(protocol)提供的。我能做些什么来解决这个问题?
谢谢!!
最佳答案
您必须将 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 "http://phonegap.com", 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);
});
});
你必须用你的 socket.io 服务器的主机名替换 HOST!
关于javascript - Socket.io + PhoneGap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10738073/