3 Replies Latest reply on Sep 7, 2017 8:06 AM by natejbeck

    AngularJS $http does not work with Developer app, works fine in browser

    natejbeck

      I am writing a Phonegap/Cordova application using AngularJS consuming a Rails API. I'm attempting to use $http to hit the API during a login event. When emulating my application on Chrome (launching using cordova run) $http works great as expected.

      However, anytime I use $http after building/using on the phone (with the PhoneGap developer app) I get some sort of pre-flight or CORS error and never even hit the API.

      Rails API is using the gem rack-cors to allow CORS - it works with several other AngularJS applications and is relatively unsafe only for debug purposes.

      # config/application.rb  
        CORS_ALLOW_ORIGIN 
      = "*"
        CORS_ALLOW_METHODS
      = %w{GET POST PUT OPTIONS DELETE}.join(',')
        CORS_ALLOW_HEADERS
      = %w{Content-Type Accept X-Auth-Token AllowedHeader}.join(',') 

        ... other config stuff ... 

        config
      .middleware.insert_before 0, Rack::Cors do
          allow
      do
            origins
      '*'
            resource
      '*', :headers => :any, :methods => :any
          end
        end 

        config
      .action_dispatch.default_headers = {
          "Access-Control-Allow-Origin"  => CORS_ALLOW_ORIGIN,
          "Access-Control-Allow-Methods" => CORS_ALLOW_METHODS,
          "Access-Control-Allow-Headers" => CORS_ALLOW_HEADERS
        }

      What I've tried: 1) update phonegap config.xml to unsafely allow anything access

      <access origin='*' 
              allows-arbitrary-loads-in-media='true'
              allows-arbitrary-loads-in-web-content='true'
              allows-local-networking='true' />
      <allow-intent href="*" />
      <allow-navigation href="*" />

      2) use angular .run to add headers for every request made

      angular.module("services")  
        .run(function($http) { $http.defaults.headers.common['AllowedHeader'] = "origin"; })

      3) manually build up each request with other headers

      login: function(credentials) { 
        var request = {
          url
      : baseURI + "/user_sessions/",
          method
      : "POST",
          params: { user_session: credentials, },
          headers
      : {
            "Cache-Control": "no-cache",
            "Content-Type": "application/json"
          }
        } 

        return
      $http(request);
      }

      4) use cordova-whitelist-plugin

      The $http request never makes it to the API - get back a "status": -1 error. Any ideas? I'm wondering if there is a config variable that I'm missing to allow for $http requests.