Reputation: 2697
I am trying to program the following Curl command using Angular JS. I'm very new to AngularJS, so I may be missing something fundamental.To be specific, this is a mobile app, that is using the ionic framework (which uses Angular JS)
The curl command is this:
curl -X POST -d "username=xxxx&password=xxxx&action=login&view=console" http://myserver.com/zm/index.php?skin=xml
This works perfectly from command line.
In AngularJS, I have the following code:
angular.module('starter.controllers').controller('MonitorCtrl', function($ionicPlatform, $scope,$http)
{
console.log("***MAKING REQUEST");
//$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http({
url:'http://myserver.com:9898/zm/index.php?skin=xml',
method:'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*',
},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
var foo= str.join("&");
console.log ("****RETURNING "+foo);
return foo;
},
data: {username:'admin',
password:'xxxx',
action:'login',
view:'console'}
})
.success (function()
{console.log("****YAY");
})
.error(function(data, status, headers, config)
{
console.log("***OOPS "+status + " H: "+data);
});
});
When I run this code, I see a POST request going to my server (I am sniffing using httpry) and a 200OK being returned from the server with the required payload, but my success handler is not being called. The error handler is called with a status of 0
Upvotes: 2
Views: 3586
Reputation: 2697
Okay, I finally figured it all out
a) Amir popovich is right in that if I am dealing with XML, I need to 'transmogrify' (transform in a magical manner, for non Calvin and Hobbes readers) JSON to XML. The updated code I posted in my question does exactly that and works. But even after doing all that, my URL post (or get) was failing.
b) The entire darn CORS error I was facing was because I was running this app in a desktop browser (Safari) and it was Safari that was kicking out the response unless it had Accept Origin
c) When I deployed and tested the app on my phone, it worked like a charm. Don't ask me why
Upvotes: 1
Reputation: 29836
data should be a json
. It depends on your server.
The common way to do it is is using properties on an object:
data: {username: 'xxxx', password: 'xxxx', action: 'login', view:'console'}
but if your server receives a string as an input then:
data: {key: 'username=xxxx&password=xxxx&action=login&view=console'}
Upvotes: 1