How to fix CORS issues, revisited

Thanks to the Ionic CLI, we have a new solution

Posted on January 14, 2015

A few months ago I wrote about how to fix CORS problems when using Ionic. I recently discovered a relatively new CLI feature for Ionic that makes it even easier to handle CORS issues while you develop locally. Do note, this feature only works with ionic serve so you will still need to handle CORS differently for production.

While working on the example for chapter 6, I started to use a RESTful API that did not support CORS. Here’s how to use the new Ionic CLI proxy feature.

Define your proxy in ionic.project

Open up your ionic.project file, which is generated by the Ionic CLI when you start a project. It is just a JSON string, and we need to add a new property to enable proxies.

1
2
3
4
5
6
7
8
{
  "name": "app",
  "app_id": "",
  "proxies": [{
    "path": "/api/forecast",
    "proxyUrl": "https://api.forecast.io/forecast/APIKEY/"
  }]
}

The proxies property accepts an array of objects, so you can create multiple proxies. Each object should have a path and proxyUrl, where path is the localhost url to call and proxyUrl is the real URL to call.

Now when you want to use this proxy, you can do so by calling the path instead of the original URL.

1
2
3
$http.get('/api/forecast/').success(function (forecast) {
  $scope.forecast = forecast;
});

Now you don’t need to setup your own proxy server, you can just use the Ionic CLI!