cs-87
cs-87

Reputation: 216

Ionic HTTP client post Request cross origin Error , But works on Postman

I am trying to perform the following post request in my ionic app , where I get following error

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

But same request works perfectly when performed using postman in the same PC. Appreciate your valuable help.

Postman Response

enter image description here

Ionic HTTP Post request

import {
    HttpClient,
    HttpHeaders
} from '@angular/common/http';

constructor(public menuCtrl: MenuController, private http: HttpClient, private router: Router, private alertController: AlertController,
    public loadingController: LoadingController) {
    window.sessionStorage.setItem("ip", "myapi.com");
}


let authorizationData = 'Basic ' + btoa(this.username.trim() + ':' + this.password.trim());
window.sessionStorage.setItem("auth", authorizationData);

const httpOptions = {
    headers: new HttpHeaders({
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json; charset=utf-8',
        'Authorization': authorizationData
    })
};

console.log(authorizationData);
this.present();


this.http.post('https://' + window.sessionStorage.getItem('ip') + '/OffsiteAtmMonitoring/login/submit', {}, httpOptions)
    .subscribe(
        data => {


            window.sessionStorage.setItem("name", data["name"]);
            window.sessionStorage.setItem("firstname", data["firstname"]);
            window.sessionStorage.setItem("lastname", data["lastname"]);
            window.sessionStorage.setItem("username", data["username"]);
    }

Upvotes: 1

Views: 2807

Answers (2)

Kaushikkumar Parmar
Kaushikkumar Parmar

Reputation: 409

Using a proxy to bypass the CORS issues with Ionic 4 is actually very easy and straightforward, all you need to do is as follows:

Use a text editor to open ionic.config.json which exists inside the root of your project.

Next add a proxies array just like in the following example

    "name": "proxy-example",
    "app_id": "id",
    "v2": true,
    "typescript": true,
    "proxies": [{
        "path": "/goto",
        "proxyUrl": "http://target-server.com"
    }]
    }

You only need to add the proxies array, leave the other values as they are in your original ionic.config.json.

The proxyUrl should contain the server you want to connect to, which presents the CORS issues.

the path is what we are going to use inside our Ionic project to send requests to the target server, the Ionic proxy will take care of proxying the requests to the actual target API server.

Upvotes: 1

Kevin
Kevin

Reputation: 2404

Your request works in postman because it doesn't send pre-flight requests. you should read https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS or else I really briefly explain how cors works at a high level in the second part of the question here, maybe you will find it useful. 405 (Method Not Allowed) and blocked by CORS policy

There is almost certainly a server issue, but you do have some headers that aren't needed.

const httpOptions = {
    headers: new HttpHeaders({
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json; charset=utf-8',
        'Authorization': authorizationData
    })
};

'Access-Control-Allow-Origin': '*' This is not required. your server should respond with this if it is allowing requests from all origins.

The server also needs to respond with Access-Control-Allow-Credentials: true if you are sending authenticating data.

There is no way to fix it on the client (ionic) side that I would deem acceptable. You could use a cors proxy but this is not an acceptable fix in my opinion

There may be ways to do a hack fix to prevent Cors requests being sent on android and ios and avoid using a proxy, I am unsure of this though. My advice is to correctly configure the API you are connecting to if at all possible. It is the only way to reliably connect to an API from a different origin

Upvotes: 1

Related Questions