Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic http post to external url

Im trying to send a post to a url with Ionic using angular, but i have the response:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 404.

I know that the external service is working, because i tested it by ajax and everything works perfectly...

Below the code used in AngularJS (Ionic) and Ajax:

Ionic:

var loginServiceUrl = 'http://url.com.br'; //It is not the real one
var loginServiceData = {
    email: [email protected]
    senha: 1234
};
$http.post(loginServiceUrl, loginServiceData).
then(function (res){
    console.log(res);
});

Ajax:

$.ajax({
    type: "POST",
    url : 'http://url.com.br', //It is not the real one
    data : {email: '[email protected]', senha: '1234'},
    success: function(result) {
        $('html').text(JSON.stringify(result));
    }
});

Does anyone know why I get the post via ajax on my localhost and not with the ionic, also localhost?

like image 734
Beto Avatar asked Oct 30 '22 00:10

Beto


2 Answers

Check this out. It is well explained how to handle issues like yours --> http://blog.ionic.io/handling-cors-issues-in-ionic/

like image 56
radioaktiv Avatar answered Nov 12 '22 16:11

radioaktiv


Try to add headers in your POST request.

//example of DataToSend

   var DataToSend = {
                    userID: deviceID,
                    coordLat : pos.coords.latitude,
                    coordLon: pos.coords.longitude
   };

   $http({
            method: 'POST',
            url: 'http://url.com.br',
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
            data: DataToSend
        })
like image 33
e7lT2P Avatar answered Nov 12 '22 17:11

e7lT2P