Meysam
Meysam

Reputation: 18177

ionic: http post request works in browser but not in mobile

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:

enter image description here

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 [email protected]

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.

Upvotes: 2

Views: 2420

Answers (1)

atakanyenel
atakanyenel

Reputation: 1375

When you upload your code to your phone ,the localhost becomes your phone, not your computer. So there is no server on your phone that listens, so it gives an error. To fix this, when trying on your phone change localhost to the IP of your computer , which you can learn by typing ipconfig in Windows and ifconfig in Linux. Write the number starts with 192.168.... or 10.... instead of localhost. That way it will also work on your computer. It is also the same reason why it works when you send it to a remote server.

Upvotes: 2

Related Questions