Ionic cordova - Cors not working on newer version of android, But its working on android 7 or 6

I am having a problem with using typescript ionic, this is my code. its working fine in browser and some of mobile phones. but its not working on newer version of androids such as 8+ version. Please help me to fix this issue

import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { HTTP } from '@ionic-native/http/ngx';
import { Platform } from '@ionic/angular';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
import {finalize} from 'rxjs/operators';
import { Observable } from 'rxjs/Observable'; 

@Injectable()
export class AccessProviders{
    server: string = 'http://example.com/api/';
    
    constructor(
        public http: HttpClient,
        public nativeHttp: HTTP
    ){}

    
    postData(body,file){
        let type = "application/json; charset=UTF-8";
        let headers = new HttpHeaders({ 'Content-Type': type });
        let options = {
            headers: headers
        }
        return this.http.post(this.server+file,JSON.stringify(body),options).map(res => res);
    }
}

My suggestions:

  • Use an https endpoint instead of http
  • Use only Angular’s HttpClient, forget about the cordova plugin
  • Stop micromanaging
  • Give proper types to everything
postData<T>(body: T, file: string): Observable<HttpResponse> {
  return this.http.post(this.server+file, body);
}

You don’t need to manually marshal and unmarshal objects to and from JSON. You don’t need to manually declare content-type. And to counter the objection of “who cares? it doesn’t hurt”: every unnecessary line of code we write (a) gives us an opportunity to mess it up and create a bug, and (b) diverts readers’ attention away from the important things our code does.

Thank you brother. Its working now.

Starting android 9 non-secure app connection disabled by default. If you really need it can be enabled by addind this line in AndroidManifest:
android:usesCleartextTraffic=“true”