Search code examples
androidangularionic5

blocked by CORS policy in ionic-5 angular


I am facing this error, can someone please guide me for the same. I have made configuration in proxy.conf.json I have set header with base url in user.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { map } from 'rxjs/operators';


@Injectable()
export class UserService {

    constructor(public http: Http) { }

    yaho() {
        const headers = new Headers();
        headers.append('Access-Control-Allow-Origin', '*');
        // headers.append('Access-Control-Allow-Credentials', 'true');
        headers.append('Access-Control-Allow-Headers', 'Content-Type');

        headers.append('Access-Control-Allow-Methods', 'GET, POST');


        headers.append('Content-Type', 'application/json');
        headers.append('appKey', '4d71e017-6896-477b-bb0d-93bb9e6d3224');
        const options = new RequestOptions({ headers });
        const baseURL = 'abx/gas.json';
        console.log('Base url---->' + baseURL);
        const url = 'localhost:8081/abx/gas.json';
        return this.http.get(url, options)
            .pipe(map(res => res.json()));
    }
}

Solution

  • You cannot fix your issue by trying to enable CORS in your client. This is a general/ fundamental feature of http and not something specific to ionic or angular. If you have no way to change the back end then you can use a proxy.

    "The Ionic CLI introduced the ability to have a proxy server issue requests for you to get around any CORS issues you may have. Since the server is sending a fresh request to your destination, there will be no origin and therefore, no CORS needed"

    as described here and example repo here

    Which I assume is how you are trying to handle CORS request without enabling it in the back end.

    Please note that "CORS is only an issue when we are running or testing our app when running ionic serve or ionic run -l."

    to setup the proxy:

    1. set up the proxies in our ionic.project
    {
      "name": "proxy-example",
      "app_id": "",
      "proxies": [
        {
          "path": "/api",
          "proxyUrl": "http://cors.api.com/api"
        }
      ]
    }
    
    1. replace our endpoint URLS to be set to the proxy server
    2. run ionic serve

    Aside from this "The easiest way to handle the CORS problem is to ultimately ask your API provider to allow all hosts"