I'm having a hard time getting Angular to do a post request that my server understands. I either need to implement a fix server side or transform the request pre flight clientside.
jQuery.post
When I do a request with jQuery it responds as expected:
$.ajax({
data: paramdata,
type: "POST",
url: 'http://api.example.com/api/controller',
dataType: 'json'
}).then(function(response) {
angular.forEach(response.errors, function(val, row) {
alert('jQuery says : ' + val);
});
});

Angular $http.post
When I do something similar in Angular it fails with Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin.
$http.post('http://api.example.com/api/controller', {
data: {'name':'Rick James'}
}).then(function(response) {
var data = response.data;
angular.forEach(data.errors, function(val, row) {
alert('$http says: ' + val);
});
});

I'm configuring my $http provider like this:
angular.module('fooApp').config(['$httpProvider', function($httpProvider) {
//Fix as described here: https://github.com/angular/angular.js/pull/1454
delete $httpProvider.defaults.headers.common["X-Requested-With"];
}]);
When I add in this line
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
it sends the data without the Acces-Control-Allow-Origin error, but the server understandably does not understand how to parse the JSON of of the application/json object.
How may I do angular $http requests that behaves more like jQuery?
.NET Controller
[AllowAnonymous]
[HttpPost]
[AllowCrossDomain]
public JsonResult JsonLogin(LoginModel model, string returnUrl)
{
//Origin = Request.Url.AbsoluteUri;
if (ModelState.IsValid)
{
if (WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
{
FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
// return Json(new { success = true, redirect = returnUrl });
return Json(new { success = true, redirect = Session["Origin"] });
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed
return Json(new { errors = GetErrorsFromModelState() });
}
We have allowed cross-domain requests wiith the AllowCrossDomain filter witch sets Access-Control-Allow-Origin, "*", Access-Control-Allow-Methods and Access-Control-Max-Age.
var xsrf = $.param(model); $http.post(url, xsrf);As xbonez pointed out Angular doesn't send data like jQuery and ASP.NET doesn't play well with it.