Cross origin resource sharing issue with Ionic app


#1

So I am trying to make http calls from my ionic application to another application running on tomcat apache serve however I think due to CORS issue the calls are not being successful. I followed the instructions on this site http://blog.ionic.io/handling-cors-issues-in-ionic/ with no luck. I am running the the tomcat apache application on http://localhost/platform/ and the ionic application on localhost:8100 I added this to my ionic.project:

{
  "name": "mobile",
  "app_id": "",
  "proxies": [
    {
      "path": "/platform",
      "proxyUrl": "http://localhost/platform/",
    }
  ]
}

Added this also to my gulpfile.js:

gulp.task('install', ['git-check'], function() {
  return bower.commands.install()
    .on('log', function(data) {
      gutil.log('bower', gutil.colors.cyan(data.id), data.message);
    });
});

gulp.task('git-check', function(done) {
  if (!sh.which('git')) {
    console.log(
      '  ' + gutil.colors.red('Git is not installed.'),
      '\n  Git, the version control system, is required to download Ionic.',
      '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
      '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
    );
    process.exit(1);
  }
  done();
});

I also added this line to my app.js:

.constant('appBaseUrl', 'http://localhost:8100/platform')

This is the http call I make:

$http({
                method: 'post',
                url: appBaseUrl + '/j_spring_security_check',
                params: {
                    'j_username': credentails.username,
                    'j_password': credentails.password
                }
            })

However, the console can’t GET the loginsuccess.json which is the response to a successful authentication with the backend server on tomcat. Here is the response on the console http://s16.postimg.org/m2ua3kqc5/console.png

I have spent an entire day trying to make this work with no luck. Btw the specifications of proxy and proxypass for http://localhost/platform/ are defined on the httpd.conf file in the apache folder


#2

From my experience, there are three easy solutions to your problem.

If you’re testing it locally use Firefox instead of Chrome. Ionic will work even under Firefox which don’t suffer from this problem. If even Firefox is not working then the second solution has a fix even for Firefox.

If you still want to use Chrome then take a look at this tutorial: https://blog.nraboy.com/2014/08/bypass-cors-errors-testing-apis-locally/

A third option, use JSONP instead of JSON (at least while you’re developing your application): http://www.sitepoint.com/working-around-origin-policy/

I understand JSONP is limited, but you only need it in your local environment, then switch back to CORS.