NativeScript Angular does not allow cleartext HTTP traffic to localhost

Currently, I am working on implementing a login system for my network using the Angular version of NativeScript. Below is the code snippet in which I am attempting to log into the network.

home.component.ts


import { LoginService } from '../Services/login/login.service';
export class LoginComponent implements OnInit {

public user: User;
loginForm: FormGroup;

constructor(private router: Router,
    private userService: UserService,
    private page: Page,
    public  loginDetails: LoginDetails,
    private LoginService: LoginService

) {

    this.user = new User();
    this.user.email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a674a6724696567">[email protected]</a>";
    this.user.password = "pass123";
    this.user.logo = "~/Images/opos_logo.png";
}

submit() {

   /* set a user variable with data from the formGroup */
   const user: string = this.user.email;
   /* set a password variable with data from the formGroup */
   const password: string = this.user.password;

   this.LoginService.loginUser(user, password)
       .subscribe(data => this.checkUser(data));
}
}

Services/login/login.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from "@angular/core";
import { Jwt } from '../../Classes/jwt';


@Injectable({
   providedIn: 'root'
})
export class LoginService {


 loginUrl = 'http://localhost/Login.w';

 constructor(private _http: HttpClient) { }

 loginUser(user, pass) {
     return this._http.get<Jwt>(
         this.loginUrl, { params: { fi_user: user, fi_pass: pass } });
 }
}

Upon running the application as it is, an error message displayed:

"originalStack": "Error: java.io.IOException: Cleartext HTTP traffic to localhost not permitted\n at new ZoneAwareError (file:///data/data/org.nativescript.preview/files/app/tns_modules/@nativescript/angular/zone-js/dist/zone-nativescript.js:1298:31)\n at onRequestComplete (file:///data/data/org.nativescript.preview/files/app/tns_modules/@nativescript/core/http/http-request/http-request.js:54:30)\n at Object.onComplete (file:///data/data/org.nativescript.preview/files/app/tns_modules/@nativescript... "

I followed the suggestions from this post on Stack Overflow to resolve the issue. I added an androidmanifest.xml file to the program by placing it in the path /App_Resources/Android/AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="__PACKAGE__"
android:versionCode="1"
android:versionName="1.0">

<supports-screens
    android:smallScreens="true"
    android:normalScreens="true"
    android:largeScreens="true"
    android:xlargeScreens="true"/>

<uses-sdk
    android:minSdkVersion="17"
    android:targetSdkVersion="__APILEVEL__"/>

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:name="com.tns.NativeScriptApplication"
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:networkSecurityConfig="@xml/network_security_config">

    <activity
        android:name="com.tns.NativeScriptActivity"
        android:label="@string/title_activity_kimera"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:theme="@style/LaunchScreenTheme">

        <meta-data android:name="SET_THEME_ON_LAUNCH" android:resource="@style/AppTheme" />

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.tns.ErrorReportActivity"/>
</application>

In addition, I also included a network_security_config.xml file as suggested by the Stack Overflow post and placed it in res/xml/network_security_config.xml.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
   <domain-config cleartextTrafficPermitted="true">
      <domain includeSubdomains="true">domain.com (to be adjusted)</domain>
   </domain-config>
</network-security-config>

I attempted to add the application android:usesCleartextTraffic="true" tag to my home.component.html to troubleshoot the error, but unfortunately, it did not resolve the issue.

Answer №1

Give this a try:

loginUrl = 'http://10.0.2.2/Login.w';

I recently came across an article that was quite informative: @EdwardGarson provided some valuable insights:

When working with the emulator, keep in mind that localhost or 127.0.0.1 points to the emulator itself, not your actual machine. It's essential to use the IP address 10.0.2.2, which is linked to your local machine.

Best regards

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

Creating a custom component in Angular 2 that includes several input fields is a valuable skill to have

I have successfully created a custom component in Angular 2 by implementing the CustomValueAccessor interface. This component, such as the Postcode component, consists of just one input field. <postcode label="Post Code" cssClass="form-control" formCon ...

Tabs on Ionic Page

I have a mobile app built with Ionic 3 and Angular that I am currently in the process of upgrading to Ionic 6. The app does not use tabs throughout, but certain pages within the app have tab functionalities. Here is a simplified example: foo.html: <io ...

Include a parameter in a type alias

Utilizing a function from a library with the following type: type QueryFetcher = (query: string, variables?: Record<string, any>) => Promise<QueryResponse> | QueryResponse; I aim to introduce an additional argument to this type without mod ...

Ways to retrieve the identifier of a specific element within an array

After successfully retrieving an array of items from my database using PHP as the backend language, I managed to display them correctly in my Ionic view. However, when I attempted to log the id of each item in order to use it for other tasks, it consistent ...

Unable to create Azure CDN Endpoint: HostName entered is invalid - Ensure it is a valid domain name, IP version 4, or IP version 6

As I work on setting up an Azure CDN endpoint using CDKTF, I've hit a roadblock with an error that I'm unable to troubleshoot. The error message I'm seeing states: Error: creating Endpoint: (Name "test" / Profile Name "test-profile" / Resour ...

Creating consistent heights for buttons and input fields in Angular Material can be achieved by adjusting the

I have a simple form with two outline fields and a button. <form [formGroup]="filterForm"> <section> <ng-container> <mat-form-field appearance="outline" class="mr-1"> ...

Generate a customizable form by utilizing a JSON file as a template. The JSON file can be easily modified by clicking a button, allowing for real-time

My goal is to develop a dynamic form using the guide provided at https://angular.io/guide/dynamic-form. I am utilizing two JSON files, namely sbb.json and gx.json. The initial creation of the form from the JSON file works flawlessly. However, I encountered ...

Looking to incorporate a pair of floating buttons within a listview widget

Currently working on an app where I need to implement two floating buttons similar to those seen on Google+. To achieve this, I am utilizing the library found at makovkastar/FloatingActionButton However, I have encountered an issue where adding a second ...

Utilizing the component as both a custom element and an Angular component

I have been experimenting with using an Angular component as a custom element, allowing me to dynamically add it to the DOM and have it automatically bootstraped. However, I also need this component to be included in another component's template. Cur ...

Utilizing Angular CLI configuration for End-to-End testing purposes

I'm currently in the process of updating an Angular CLI project to version 6 The issue I'm facing is that prior to version 6, I could run the command ng e2e -e=e2e and the tests would execute smoothly with the specified environment. However, in ...

Tips for utilizing single quotation marks while logging multiple variables in console

When I write console.log("entered values are "+A+" and "+B); the tsLint gives a warning that single quotes should be used. However, I discovered that if I use single quotes, I am unable to include multiple variables in the same console ...

Tips and Tricks for Setting Up Angular 2

I'm currently attempting to set up Angular 2 following the official Angular 2 documentation and various resources, but I'm encountering some roadblocks. Can anyone offer guidance on configuring the Angular 2 environment in Visual Studio or anothe ...

Error: ndk-build is unable to find a target rule for compiling protobuf

I've been encountering some challenges while using ndk-build to integrate my protobuf library for Android Development. Despite obtaining my Android.mk file from a previous stackoverflow thread, it appears that the setup is not functioning correctly. I ...

What could be causing my mdx files to not display basic markdown elements such as lists and headings? (Next.js, mdx-bundler)

Trying to implement Kent C Dodds mdx-bundler with the Next.js typescript blog starter example is proving challenging. While it successfully renders JSX and certain markdown elements, basic markdown syntax like lists and paragraph spacing seem to be malfunc ...

Breaking down code with Webpack for future extensibility

We are in the process of developing a game and have successfully implemented code-splitting to separate vendor libraries and the core engine into individual bundles, as well as splitting levels into separate bundles. As we plan for future releases where t ...

Struggling with incomplete data loading from SQLite DB into Android ListView

I've been developing an interactive Android app called PersistAlarm to help users set alarms with ease. The main feature of the application is a button that leads to a ListView where alarms can be added and managed. Once an alarm is set, it gets store ...

Tips for configuring the navigation links on the current page using Bootstrap

In my Angular application, I have set up navigation links for home, about, notifications, and logout. However, when I click on the home link, it redirects me to the login page instead of remaining on the current page. I need the functionality to stay on ...

Getting a local JavaScript file to load in WebView on Android

I need help with a program I'm working on that involves creating a simple toast. Initially, when I added the script directly into the HTML, it worked perfectly and displayed the toast. However, when I moved the same script to a separate file under the ...

The module `perf_hooks` could not be resolved

Trying to integrate perf_hooks library from the nodeJS Performance API into my React Native project has been quite a challenge. Here's the snippet of code I've been working with: import {performance} from 'perf_hooks'; export const mea ...

Angular: Streamlining the Constructor Function for Efficiency

Consider the scenario where we have these two components: export class HeroComponent { constructor( public service1: Service1, public service2: Service2, ) { // perform some action } } export class AdvancedHeroComponent extends HeroCompone ...