我需要在ionic2应用程序中使用socket.io连接。
我通过npm安装了socket.io-client,所以我可以这样使用它。
import * as io from 'socket.io-client'
...
...
this.socket = io(this.conf.connectionServer);
this.socket.on('connect', () =>{
...
...})
当我ionic serve
在chrome上使用或运行离子run -l
时,我确实可以工作,但是当我只使用离子运行build
或run
一切都可以时,它将无法正常工作。
我能够在我的android设备的屏幕上记录错误信息:
Error: Failed to execute: open: on :XMLHttpRequest:: Refused to connect to : http://file/socket.io/?EIO.....: because it violates the documents Content Security Policy.....
我的内容安全政策是:
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; ;
style-src 'self' 'unsafe-inline';
script-src 'self' 'unsafe-inline' 'unsafe-eval'
http://localhost:*
http://127.0.0.1:*
;
connect-src 'self'
ws://*
http://141.xx.xx.25:*
http://*.foobar.de
http://file/socket.io*
;
img-src *;
media-src *
">
但是我找不到正确的解决方案。
在Chrome中,连接转到:http://141.XX.XX.25/socket.io/,但在android上,它尝试连接到http://file/socket.io/
即使将其设置为default-src *;
Socket.io-Connection也仅在使用Serve
或run with the Livereload-option
我正在使用:
Cordova CLI: 6.0.0
Gulp version: CLI version 3.9.1
Gulp local:
Ionic Version: 2.0.0-beta.1
Ionic CLI Version: 2.0.0-beta.17
Ionic App Lib Version: 2.0.0-beta.8
OS:
Node Version: v5.6.0
这个问题与CSP并不完全相关:原因是socket.io连接的设置:
//this is wrong
this.statisticServer= "141.xx.xx.xx:8090/";
..
this.socket = io(this.conf.connectionServer);
但是应该是:
//this is right
this.statisticServer= "http://141.xx.xx.xx:8090/";
...
this.socket = io(this.conf.connectionServer);
因此必须将http声明为协议...可能是一个错误
作为CSP,可以使用:
<meta http-equiv="Content-Security-Policy" content="
default-src *;
style-src 'self' 'unsafe-inline';
script-src * 'self' 'unsafe-inline' 'unsafe-eval';
connect-src * ;">
该CSP几乎可以在任何地方提供一切。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句