使用Vue.js+Cordova创建安卓应用,打开时出现连接错误如何解决?
问题描述
使用Vue.js和Cordova开发安卓应用,打包后打开应用时弹出连接错误提示,相关配置如下:
相关配置
.env配置文件
VUE_APP_URL='https://myapp.com'
cordova/config.xml配置文件
<?xml version='1.0' encoding='utf-8'?> <widget id="com.mealclub.app" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> <name>UkMeals</name> <description> A sample Apache Cordova application that responds to the deviceready event. </description> <author email="dev@cordova.apache.org" href="http://cordova.io"> Apache Cordova Team </author> <!-- this hook will point your config.xml to the DevServer on Serve --> <hook type="after_prepare" src="../node_modules/vue-cli-plugin-cordova/serve-config-hook.js" /> <content src="index.html" /> <access origin="*" /> <allow-intent href="http://*/*" /> <allow-intent href="https://*/*" /> <allow-intent href="tel:*" /> <allow-intent href="sms:*" /> <allow-intent href="mailto:*" /> <allow-intent href="geo:*" /> <platform name="android"> <allow-intent href="market:*" /> </platform> <platform name="ios"> <allow-intent href="itms:*" /> <allow-intent href="itms-apps:*" /> </platform> </widget>
错误截图

故障原因及排查修复方案
- 安卓高版本网络安全规则限制
安卓9及以上版本默认禁止非HTTPS的明文流量,即使你用的是HTTPS域名,也需要配置网络安全规则放行相关域名。
修复:在cordova/platforms/android/app/src/main/res/xml下新建network_security_config.xml文件,内容如下:
然后在config.xml的widget标签头部添加安卓命名空间声明:<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">myapp.com</domain> </domain-config> </network-security-config>xmlns:android="http://schemas.android.com/apk/res/android",再在android平台配置块中添加以下配置,让应用引用网络安全文件:<edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application"> <application android:networkSecurityConfig="@xml/network_security_config" /> </edit-config> - Vue项目资源路径配置错误
修复:检查vue.config.js中的publicPath配置,Cordova打包时必须设置为./相对路径,不能使用默认的/绝对路径,否则打包后本地资源加载失败。 - 白名单插件缺失
虽然你已经在config.xml中配置了访问权限,但需要确认已安装cordova-plugin-whitelist插件,执行cordova plugin ls检查,未安装的话执行cordova plugin add cordova-plugin-whitelist安装后重新打包即可。 - 请求时机错误
修复:Vue实例初始化逻辑必须放在Cordova的deviceready事件回调中执行,否则Cordova权限未加载完成就发起网络请求会触发报错,示例代码:document.addEventListener('deviceready', () => { new Vue({ render: h => h(App) }).$mount('#app') }, false) - 打包命令错误残留调试配置
你配置中的after_prepare hook是开发调试阶段用来指向本地开发服务的,生产打包时不要使用cordova-serve类调试命令,要使用生产构建命令。打包前可先删除platforms文件夹再重新添加安卓平台,避免旧调试配置残留。
内容的提问来源于stack exchange,提问作者user6085744
相关产品推荐
相关产品推荐

