Brentg
Brentg

Reputation: 1569

Setting up CORS in Ionic

I'm in the process of creating my first ionic app, but I'm struggling with cors, I don't have a lot of experience on this area, so this question may seem stupid.

I do not have access to the api site, so I can't change anything there. This is the code I am using to get the data from the api site. I've read that the cors is only a problem when testing with ionic serve, but I've tried building the android app and transferring the apk to my phone, but it doens't seem to work there either (and I can't see the console log on my phone offcourse to test it :) )

  app.controller('VolleyCtrl', function($http, $scope) {
      $scope.wedstrijden = [];
      $http.get('http://www.volleyadmin2.be/services/wedstrijden_xml.php?province_id=5&stamnummer=O-0696&format=json')
        .success(function(response) {
          angular.forEach(response, function(child) {
            $scope.wedstrijden.push(child);
          })
        });

  });

Upvotes: 4

Views: 2156

Answers (3)

Samaludheen
Samaludheen

Reputation: 176

After trying a lot of solutions without luck, finally

cordova plugin rm cordova-plugin-ionic-webview
cordova plugin add cordova-plugin-ionic-webview@latest

solved issue in my case.

Upvotes: 1

mammuthone
mammuthone

Reputation: 59

There could be a lot of reason.

Handling CORS mean configuring backend and frontend. In your backend, depends on which web server your api is running.

I don't think you're going to solve using the "...you can disable it checking for cors by opening it with --disable-web-security flag..."

It will be a good practice to handle only an http promise in controller and move the http request on a service. I can tell you what I fixed to avoid the CORS preflight trouble.

By default, Angular set headers in $http.defaults.headers.{HTTP_VERB}.

My case was $http.defaults.headers.post with a 'Content-type' : 'application/json'. This kind of content type was triggering the cors in chrome. Doesn't matter if you set 'Content-Type' manually. This is set by default in Angular.

So the fix is go to your app.js file and inside the .config section insert your code that will be a kinda of

app.config(['$http', function ($http) { //Reset headers to avoid OPTIONS request (aka preflight) $httpProvider.defaults.headers.post = {}; }]);

Upvotes: 0

MHX
MHX

Reputation: 1601

If you're using a newer version of Cordova (or the latest Ionic CLI) to develop your app, you may be experiencing http 404 errors when your app tries to make network requests.

This can be solved quickly with Cordova Whitelist plugin.

You can find more documentation on Ionic docs: Cordova Whitelist.

Solution:

Run the following command in your shell/terminal:

ionic plugin add https://github.com/apache/cordova-plugin-whitelist.git

The only thing you need to do now is to add a property to your config.xml file:

<allow-navigation href="*" />

Upvotes: 3

Related Questions