Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ionic app cannot connect cors enabled server with $http

I am trying to build a mobile app with ionic framework. When my application tries to connect server to get json ( server is web api and cors is enabled) it just returns 404 on genymotion and real device. But when I run application in browser with ionic serve everything work fine.

I am pretty sure CORS is functional. Here response header I got while application working in browser.

Response

Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:395
Content-Type:application/json; charset=utf-8
Date:Fri, 08 May 2015 20:24:04 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/7.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET

Request :

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, lzma, sdch
Accept-Language:tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
DNT:1
Host:*******:14400
Origin:http://192.168.0.28:8100
Pragma:no-cache
Referer:http://192.168.0.28:8100/

Config.xml has <access origin="*"/> this line in configuration

in my app.js I removed X-Requested-With headers for all http calls.

.config(['$httpProvider', function($httpProvider) {

        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];  
    }
])

I simple use get requests to server in my factory classes.

$http.get(serverPath + "/api/mobilerest/mainPage");

When I run application in Genymode or real device, response is 404 and statusText is 'not found'. I am pretty sure web api is working, the cause for this behaviour is in ionic based apps, my app is local file and protocol is file:/// so Origin header is null the in request, then server returns 404. I also tried a local file without any server I get the same error like in application.

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
DNT:1
Host:server:14400
Origin:null
Pragma:no-cache

Am I missing something ?

like image 505
adt Avatar asked May 08 '15 21:05

adt


1 Answers

cordova-plugin-whitelist seems to be "mandatory" at present.

install it :

cordova plugin add cordova-plugin-whitelist

configure config.xml

You can keep your current setup with * or change for more restrictive rules

add a html policy on index.html, you shall add a Policy also. To authorise everything, here it is :

 <meta http-equiv="Content-Security-Policy" content="default-src *;
 style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'
 'unsafe-eval'"
like image 61
aorfevre Avatar answered Oct 16 '22 12:10

aorfevre