Http post request works in browser but not in mobile


#1

I am calling a simple authentication API in my application using $http.post.

 this.login = function(scope, credentials) {
     var url = REST_API.DOMAIN + REST_API.LOGIN;
     $http.post(url, $.param(credentials)/* convert from json to query string */, {
         headers: {
             'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
         }
     })
     .success (function(response){
         $log.info(response);
     })
     .error(function(data, status, header, config){
          $log.error(data);
     });
}

My code works seamlessly when I test it in browser using the following command:

ionic serve

But when I launch it in my phone:

ionic run -lc android

The error callback function is called immediately with response data being null:

This piece of code used to work but at some point in time it’s stopped working. The only thing I remember doing that could have affected this behavior is installing newer version of android:

cordova platform remove android
cordova platform add android@5.1.1

Another point that I’ve noticed: I am sending the http request to a web service on localhost. But if I host the webservice code on a remote server the http request will work successfully on my phone.


#2

your device is its own localhost!

localhost is the current device you are on…
you should make your api public in your local network ,so your device can access your api through:

localPCIpAdress/...


#3

Thanks localhost was the problem :slight_smile:


#4

localhost API’s will not work with Device you need to host those API over internet


#5

I have the same problem but i got 404 error(http://myapi…) how it will solve please help me to solve.
thank you