cordova使用http协议打开页面(cordova结合qiankunJs)

起因

  1. cordova的webview默认使用file协议打开页面
  2. qiankunJs无法(基于fetch)使用file协议加载子应用
  3. Cookie也无法在file协议下使用

双击页面以file协议打开qiankun项目,将无法加载子应用,会报如下错误

registerServiceWorker.ts:29 Error during service worker registration: TypeError: Failed to register a ServiceWorker: The URL protocol of the current origin ('null') is not supported

参考

qiankun 是否支持前端离线包本地加载
混合应用:从 file 协议到本地 HTTP 服务器
cordova-plugin-ionic-webview跨域问题

解决办法

因为cordova几乎没人维护,但是因为优秀的思路被ionic团队看重,并为期续命。
所以,为cordova编写一个可以在原生内部起服务的形式打开页面(即http访问页面的)插件cordova-plugin-ionic-webview

cordova plugin add cordova-plugin-ionic-webview
npm install @ionic-native/ionic-webview

安装完成,再次打开,页面将是以http的形式打开。
协议默认http
域名默认localhost
端口默认80
若无特殊要求,无需任何配置即可。

注意事项

  1. 默认cordova是支持跨域,因为在config.xml中这句话就是允许跨域
<access origin="*" />

但是使用cordova-plugin-ionic-webview即出现跨域现象,
解决办法:最简单的就是让后端放开跨域或者nginx代理跨域即可。

  1. nginx代理后出现如下跨域错误的
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by ...

把vue项目中的axios.defaults.withCredentials = true; 删除即可
建议前后端分离的项目,用token代替cookie,从而避免过多坑

预览

posted @ 2021-07-16 14:48  丁少华  阅读(1697)  评论(0编辑  收藏  举报