15

I am having a CORS issue with Ionic 3 when attempting to make GET calls to an API. I am using Ionic local server, running ionic serve in the command line for live server.

Error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

I tried updating ionic.config.json with proxy setting but that does not seem to be working..

{
  "name": "projectLeagueApp",
  "app_id": "47182aef",
  "type": "ionic-angular",
  "integrations": {
    "cordova": {}
  },
  "proxies": [
    {
      "path":"/games",
      "proxyUrl": "https://api-2445582011268.apicast.io/games/"
    }
  ]
}

My Data Service

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


@Injectable()
export class DataProvider {

  headers = new Headers({'user-key': '1234567890123'});
  options = new RequestOptions ({headers: this.headers}); 
  limit: number = 50;

  constructor(public http: Http) {
    console.log('Hello DataProvider Provider');
  }

  getGames(genre, offset_num) {

    let genre_id = genre;
    let offset = offset_num;

    return this.http.get('https://api-2445582011268.apicast.io/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)
  }

}

I am trying to make calls to this api

Request Url

https://api-2445582011268.apicast.io
HEADERS
Key Value
user-key    YOUR_KEY
Accept  application/json

Primary Question My calls are failing. How do I create proxy for this issue?

Chris Simmons
  • 249
  • 2
  • 7
  • 19
  • 1
    Try changing the url in the `http.get` request to `/games`. The proxy will replace it with the real one. – emroussel Oct 16 '17 at 18:55
  • Duplicate: https://stackoverflow.com/questions/41861105/handling-cors-issues-in-ionic – Ari Oct 16 '18 at 01:58
  • Possible duplicate of [Handling CORS Issues in Ionic](https://stackoverflow.com/questions/41861105/handling-cors-issues-in-ionic) – Ari Oct 16 '18 at 01:58

7 Answers7

20

To fix this issue, please change the following lines

ionic.config.json

{
  "name": "projectLeagueApp",
  "app_id": "47182aef",
  "type": "ionic-angular",
  "integrations": {
    "cordova": {}
  },
  "proxies": [
    {
      "path":"/games",
      "proxyUrl": "https://api-2445582011268.apicast.io/games"
    }
  ]
}

You have to remove the " / " which is at the end of of "proxyUrl".

My Data Service

return this.http.get('/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)

In the http call, the url should begin with '/games'. '/games' because ionic will proxy http://localhost:<port>/games to https://api-2445582011268.apicast.io/games

Please use the above method for external GET and POST calls in your application.

Thank you.

Alvin Chettiar
  • 609
  • 5
  • 14
  • Glad to help. @ChrisSimmons Please upvote this answer so that developers with similar queries can get a solution from this. – Alvin Chettiar Oct 17 '17 at 20:21
  • @AlvinChettiar and Chris Sommons, thanks so much for this full example. It made perfect sense and solved my problem too. the documentation on the official site meant nothing until I saw this full example. Thanks again. – vr_driver Apr 24 '18 at 14:30
  • 1
    Just a friendly note too - remember to `ionic serve` or `ionic lab` after making changes to the ionic.config.js - it won't take effect like other code changes without "restarting" :) – Grant May 17 '18 at 03:52
  • @Grant, you mean stopping and running ionic serve again? I'm following similar steps and I'm still having troubles getting proxy to work. – Emulic May 17 '18 at 21:28
  • @Emulic correct - just CMD+C or CTRL+C and cancel the running serve, make sure your proxy changes are made then run ionic serve or ionic lab again. Treat it like an alias that has to be committed & the service has to be restarted to use it. – Grant May 18 '18 at 00:35
  • @Emulic, can you copy paste your code here so that we can find what can be fixed in your code? – Alvin Chettiar Jun 10 '18 at 04:27
  • @Alvin Chettiar. Thanks. I've made these changes but i'm getting an error when I run ionic lab "Failed to read the projects ionic.config.json file: Parameter "url" must be a string, not undefined" however I dont have a url parameter. this is my file: { "name": "ionicStarWarsApp", "app_id": "", "type": "ionic-angular", "integrations": { "cordova": {} } , "proxies": [ {"path": "/api", "proxyURL": "https: //swapi.cp/api"} ]} (Note: i left a space after https: there in my comment so i could display the proxyURL properly) – Sarah Jul 12 '18 at 10:20
2

To test in development environment, you can run Google Chrome in disable-web-security mode.

Steps to follow (On Windows)

  • Press Windows Key + R to open Run window.
  • Enter/input following command and press Enter key.

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

Steps to follow (On Ubuntu)

  • Kill all the chrome.exe instances before you run/execute it.

chromium-browser --disable-web-security --user-data-dir="[some directory here]"

  • Before Chrome 48

chromium-browser --disable-web-security

Steps to follow (On Mac)

  • Run following command in terminal.

open -n -a "Google Chrome" --args --user-data-dir=/tmp/temp_chrome_user_data_dir http://localhost:8100/ --disable-web-security

1

If you wan to use for testing in Chrome just install chrome extension Allow control origin Quick and easy way

Saurabh Ahuja
  • 473
  • 3
  • 13
0

the proxy functionality expects that you're referencing the local server. in your GET request, you're still pointed at the remote API. If you change your code to this.http.get('/games/...' it should start to function as the request will go to http://localhost:8100/games..., which the "proxy" option will catch and pass on to the URL you've provided.

You may also only need to put https://api-2445582011268.apicast.io in the proxyUrl field. I think the rest of the path is passthrough.

Jeff Woodard
  • 647
  • 8
  • 15
  • Hey Jeff, I did what you asked. I changed the proxyUrl to just 'https://api-2445582011268.apicast.io' and I am no longer receiving CORS issue. I am now having another issue. I am receiving a new error - "Runtime Error Unexpected token H in JSON at position 0". I am not sure why I am receiving this error. – Chris Simmons Oct 16 '17 at 21:34
  • Take a look at your request via chrome dev tools Network tab. What's the HTTP response code? You may see more information in there. Also, not sure if you see anything in the console indicating that the proxy was handling the request. Maybe more information there. Also, I'd recommend using ARC or Postman or some REST client to hit your proxy service configured similarly to what you see in the network tab. Might be easier to debug the API calls there. – Jeff Woodard Oct 17 '17 at 09:15
0

```
export function getAuthHttp(http: Http, options: RequestOptions) {
  console.log("token",storage.get('id_token'));
  return new AuthHttp(new AuthConfig({
          headerName: 'Authorization',
          headerPrefix: 'bearer',          
          tokenName: 'id_token',
          tokenGetter: (() => storage.get('id_token')),
          noJwtError: true,    
          //globalHeaders: [{'Accept': 'application/json'}],
          globalHeaders: [{'Content-Type':'application/json'},{"Access-Control-Allow-Origin": "*"}],
         
        }), http, options);
}
```

0

My CORS issue got FIXED when I updated Android System Webview from the play store. I tried Cordova-Advance-HTTP Plugin but my PUT Request was not working with Cordova-Advance-HTTP plugin.

After Updating Android System Webview I used HTTP Client plugin which I was using before. Updating Android System Webview helped me in CORS issue

pawan vedak
  • 157
  • 1
  • 5
-1

You can handle the CORS when debugging in browser by using CORS extension or by disabling the security of Chrome. But you need to handle the CORS when you debug in app on the server side, I was consuming woo-commerce API ,so i edited it as follows->

1.Plugins->editor->woocomerceapi

right after

<?php**
header(“Access-Control-Allow-Origin: *”);   

2.Update File

Musab
  • 1,067
  • 12
  • 12