Working on a local development environment using ionic serve
or ionic run/emulate -l -c
with livereload activated, Ionic sets up a local server on port 8100 by default (http://localhost:8100/
). The origin
at this point is localhost:8100
, which leads to external services with CORS enabled considering the request as untrustworthy and rejecting it.
As per recommendations from Ionic themselves (), one can establish a proxy alias within the Ionic application to redirect API calls, thus bypassing the origin
issue. Nevertheless, their instructions were specific to Ionic 1, so here's an updated version for Ionic v2.
Setting Up a Proxy in Ionic v2
Edit ionic.config.json
and incorporate the following proxies
configuration.
{
"name": "project-name",
"app_id": "xyz-projectid",
"v2": true,
"typescript": true,
"proxies": [{
"path": "/api",
"proxyUrl": "https://the-real-api-host.com"
}]
}
In this scenario, we are establishing a route within the Ionic app at /api
, where requests will be forwarded to the endpoint https://the-real-api-host.com
. If you wanted to utilize a different API endpoint like http://my-custom-api.com/api/v2/
, you could substitute it within the proxyUrl
field.
Adjusting API Endpoint References
You must now update all references of the base URL for the API endpoint from https://the-real-api-host.com
to /api
in your app code. Calls to /api
should be intercepted when working with Ionic serve, and redirected to the actual address.
Every project's implementation may differ. In my situation, I didn't have authority over the API since it was an external service, preventing me from managing CORS responses.
Note: Remember to restart the server (ionic serve
) or else you'll encounter 404 errors from your API calls due to them not being proxied yet.