Http.get() 在 Ionic 4 的 build(Release/Debug) 中工作但不工作

Http.get() working but not working in build(Release/Debug) in Ionic 4

我正在尝试从一个简单的 api 获取数据,它在 ionic serve(浏览器)中工作正常,但是当我构建应用程序时,http 调用不起作用.我的代码是

this.http.get("http://example.com/api/routes").subscribe(response => {
 this.routes = response["routes"];
 for (let x in this.routes) {
 let a = this.routes[x].rou_stops;
 let b = a.split(",");
          for (let y in b) {
            this.newCit.push(b[y]);

          }
        }
   });

请帮忙解决这个问题。

我认为您可以将 Native HTTP plugin 用于设备用例:

ionic cordova plugin add cordova-plugin-advanced-http
npm install @ionic-native/http

文档中的用法:

import { HTTP } from '@ionic-native/http/ngx';

constructor(private http: HTTP) {}

...

this.http.get('http://ionic.io', {}, {})
  .then(data => {

    console.log(data.status);
    console.log(data.data); // data received by server
    console.log(data.headers);

  })
  .catch(error => {

    console.log(error.status);
    console.log(error.error); // error message as string
    console.log(error.headers);

  });

我猜你得到这个是因为 android 改变了它的 http 架构。

要使其在 Android 上运行,请转到您的项目根文件夹。

你的应用文件夹 > 资源 > android > xml > network_security_config.xml 更改您的网络安全配置以破坏代码。

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

这适用于 Ionic 4 应用程序。

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

IONIC 5 更新

我在 Ionic 5 中遇到了同样的问题,但由于 HttpClient 没有捕捉到错误(我只是返回了一个未知的失败响应)而变得更加复杂。

为了确认这确实是一个 cleartext 错误,我首先不得不为 Native HTTP 插件更改 HttpClient。

在 Ionic 5 中,您现在可以在 capacitor.config.json 文件中启用明文或用 .ts 版本替换现有的 json 文件:

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
                 appId: 'com.company.appname',
                 appName: 'My Capacitor App',
                 webDir: 'www',
                 server: {
                           'cleartext': true
                         }
              };

export default config;

docs

这些答案中的大多数虽然可以工作,但不是安全选项,因为它们会打开非 https 流量。

明文仅适用于实时重新加载的本地测试,不应用于生产应用程序。

真正的解决方案是使用 HTTPS 端点或通过 let's encrypt 在您自己的服务器上设置 HTTPS。