jeewan
jeewan

Reputation: 1605

AngularJS $resource POST call on Cordova not working on iOS/Android devices but working on browser

I have the following code to make a "POST" on my end point as follows:

var response = $resource(serviceURL, {}, {
        get: {
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            transformRequest: function(obj) {
                var str = [];
                for(var p in obj) {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
                return str.join("&");
            }
        }
    });

response.get({
        grant_type : grantType,
        client_id : clientId ,
        client_secret: clientSecret,
        username : username,
        password : passwordValue
    }, function(data) {
        alert("Authenticated ...");
    }, function(error) {
        alert("Error");
    });

This code for authenticating the users works in the desktop browsers (tested on Chrome) but it is the same code for my Cordova iOS and Android project, but on devices/simulator/emulator, it only executes the fail method.

I have checked the Cordova's config.xml file and it's not a cross domain issues (I have < access orogin="*" /> in the config.xml file).

I have been trying to resolve this for hours but still no luck.

Why is it only failing in devices/emulator/simulator but works in browsers ???

Upvotes: 1

Views: 792

Answers (2)

jeewan
jeewan

Reputation: 1605

Ok, I resolved this issues but I am still not sure it will be the best solution as I see some JS error on console saying "Refused to set unsafe header 'Origin'". I simply set the header's Origin property with some valid https URL as follows:

headers: {
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Origin": "https://www.google.com"
        }

and that worked for me.

Upvotes: 0

OneZeroOne
OneZeroOne

Reputation: 147

Since cordova-android 4.0.0 you MUST install whitelist plugin. That is, you have to run cordova plugin add cordova-plugin-whitelist and everything should be working fine.

Whitelist functionality is revamped

You will need to add the new cordova-plugin-whitelist plugin to continue using a whitelist Setting a Content-Security-Policy (CSP) is now supported and is the recommended way to whitelist (see details in plugin readme). Network requests are blocked by default without the plugin, so install this plugin even to allow all requests, and even if you are using CSP.

Should you need further explanation, please refer to Cordova Android 4.0.0 release

Upvotes: 2

Related Questions