Wednesday 24 June 2015

Resolve CORS issue in ionic

 What is CORS?


Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated.


Dealing with CORS in Ionic

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


We resolve this by using a proxy server. Let’s look how the Ionic CLI provides
an easily configurable proxy server.

The Ionic CLI proxy server

A quick definition about proxies:

In computer networks, a proxy server is a server that acts as an intermediary for requests from clients seeking resources from other servers.

What we did need to do to get around these CORS issues is have a proxy server that will take our requests, issue a new request to the API endpoint, receive the response, and forward it back to our app so we can get around CORS issues.

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. It is important to note that the browser adds in the Origin header.

 

Set up your ionic.project file to be something like:

Now you can add the following code in ionic.project  in your ionic project.


{
  "name": "demo",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://demo.api.com/api"
    }
  ]
}
Here in proxyUrl you will set your url where you want to hit.

Now in production_url you will set your localhost url, in service.js.

For example-

  production_url: 'http://localhost:8100/api'

No comments:

Post a Comment