The Http.get() function is running smoothly, yet encountering issues when it comes to functionality within the build (Release/Debug)

Currently, I am facing an issue with fetching data from a simple API. Strangely, the functionality works perfectly fine when testing in ionic serve (browser). However, upon building the app, the HTTP call fails to work. Below is the snippet of my code:

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]);

          }
        }
   });

If anyone has encountered a similar problem before or knows how to resolve this issue, your assistance would be greatly appreciated. Thank you.

Answer №1

It seems like the issue you are experiencing is due to recent changes in Android's http architecture.

To resolve this on Android, navigate to the root folder of your project.

In yourAppFolder > resources > android > xml > network_security_config.xml, update the network security config with the code below:

<?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>

Answer №2

Latest Update for IONIC 5

Dealing with a similar challenge in Ionic 5 was quite tricky, especially because HttpClient wasn't handling the error properly (resulting in an unclear failed response).

To pinpoint the issue as a cleartext error, I had to switch from using HttpClient to the Native HTTP plugin.

In the new version of Ionic 5, you have the option to enable cleartext in the capacitor.config.json file or replace it with a .ts version:

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

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

export default config;

Read more here

Answer №3

If you're looking to handle device-specific use cases, consider using the Native HTTP plugin.

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

Here's how you can use it:

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);

  });

Answer №4

This solution has been effective for my usage within the framework of Ionic 4.

https://i.sstatic.net/abc123.png

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

Answer №5

While some of the suggestions provided may be functional, it is important to note that they present security risks as they allow non-https traffic.

Cleartext should only be used for local testing purposes with live-reload and not implemented in production applications.

A more secure approach would involve utilizing HTTPS endpoints or configuring HTTPS on your server using Let's Encrypt.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

how to style field color for invalid input in angular reactive forms

I am currently working with ReactiveForms and I am having trouble finding a way to modify the color of the form field outline when the input is considered invalid. It is important for me to adjust this color because the current red shade does not blend we ...

Ways to merge two distinct arrays [Angular and Typescript]

I am faced with a task where I need to merge two array lists in order to create a new array list that contains all the values associated with a common UUID in both lists. The final list should include all the values linked to the UUID in each of the origin ...

What is the process for defining a type that retrieves all functions from a TypeScript class?

Imagine having a class called Foo class Foo { bar(){ // do something } baz() { // do something } } How can you define a type ExtractMethods that takes a class and returns an interface or type containing the class methods? For example: t ...

Automatically generate user clicks within primeng pagination

I am implementing primeng's p-dataview component with pagination to display user test questions. <p-dataView [value]="userTestQuestions" [paginator]="true" [rows]="1" [totalRecords]="totalTestQuestions"> <ng-template let-question pTempl ...

Steps for utilizing a function from the parent component to initialize TinyMCE

I have implemented an uploading function in my parent component. As I set up tinymce, I connected the [init] property of my component to the loadConfig() function. <editor [(ngModel)]="data" [init]="loadConfig()"></editor> The loadConfig func ...

Storing information in firebase using data structuring

While I initially passed an array to Firebase to store data, it proved to be inefficient when querying the data. As a result, I am now considering storing the data in mapping format. However, I am unsure of how to proceed with this. { "ClassDetails": ...

Tips for configuring the node_modules/lib path in an AngularJS project

I have been trying to see if the image is working properly. Is there a way to utilize global libraries for node_module? The installation seems to be in the correct place - c:\user\AppData\Roaming\npm\node_modules However, I a ...

Can Angular i18n facilitate language switching?

My objective is to switch the language from English (United States) to Indonesia using a button. View Source Code https://i.sstatic.net/0YlfWaCY.gif The issue is that the tutorial does not cover how to implement the language change feature. Why opt for ...

"Angular EventEmitter fails to return specified object, resulting in undefined

As I work on a school project, I've encountered a hurdle due to my lack of experience with Angular. My left-nav component includes multiple checkbox selections, and upon a user selecting one, an API call is made to retrieve all values for a specific " ...

How to use Angular 8 Form Builder to upload an array of multiple images

My product form includes various fields like product name, description, and an array of images. Product Form Product Name - Product Description Product Purity - Product Commodity Images (Add) Checkbox 1 - Image 1 Checkbox 2 - Image 2 Checkbox 3 - ...

AWS CodePipeline encounters a failure with the error message: "Debug Failure. A non-string value has been passed to `ts.resolveTypeReferenceDirective`."

Everything was running smoothly, but suddenly after pushing some changes, my pipeline started failing consistently. The code works fine on my local machine, so I'm not sure what triggered this sudden issue. Here's the error message from the faile ...

Working with Union Types in the state of React's Context API using TypeScript

I'm facing an issue where TypeScript is not recognizing the existence of the property state.recipes when I use the state in another component. This seems to occur when YummlyState is the type of RecipesState. I have a hunch that YummlyState always def ...

Securing routes in Angular without relying on LocalStorage or Cookies by implementing an Auth Guard

Currently, I am working on implementing an authentication guard in Angular. Instead of the conventional method of checking local storage or cookies to verify user authentication, I am utilizing API endpoints that respond with 200 OK if a httponly cookie co ...

Having trouble minifying the bundle on the most recent version of Angular 2 with JSPM

Encountering an issue with minifying the bundle in the latest Angular 2 version using jspm... Here's the error message: events.js:160 throw er; // Unhandled 'error' event ^ GulpUglifyError: unable to minify JavaScript at cr ...

What could be causing the sudden triggering of ngOnInit in Angular 4?

After sending a request to the server, ngOnInit() { this.service.get(1).subscribe((response) => { this.whenDateCurrent = new DateCustomDate(); }); } Within the same component, there is a method that retrieves this.whenDateCurrent: public getCurre ...

A singular form featuring a duo of clickable options

Having a form with two buttons and a parameter that takes different values depending on the pressed button, how can I handle this situation? If I use the following code: <form> <input type="hidden" name="method" value="saveXml"/> < ...

What is the best return type to use for a TypeScript function that returns an AsyncFunction?

From my experience, this code should work just fine... let DynamicFunction = Object.getPrototypeOf(dynamic function(){}).constructor; export function generateJsFunction(event: string, body: string[]): any { return new DynamicFunction(body.join("\n ...

Modify the dynamic style of an Angular input field

Looking for assistance with a text box <input type="text" [ngStyle]="(show_div===true) ? {'border-color':'red','color':'red'} : {'border-color': 'green','color':'g ...

Ways to confirm the visibility of a web element on the screen with serenity-js

In the current project, I am utilizing the Serenity-js BDD framework with a screenplay pattern approach. However, I am encountering an issue when attempting to assert the visibility of an element on a web page using the "that" method from the Ensure class. ...

Is the submit input type malfunctioning in JavaScript?

I am currently working on creating a dynamic form using JavaScript. The form will present a question with two possible answers, followed by a submit button. Here is the HTML structure I have implemented: <div class="intro py-3 bg-white text-center"> ...