2

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);
    });

});

jQuery fiddler report

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);
        });
});

Angular http fiddler report

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.

1
  • If you are using jquery in conjuction with AngularJs then do something like this 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. Commented Apr 9, 2013 at 23:16

1 Answer 1

1

This is, most likely, happening, because Angular does not send data as kay-value pairs as your jQuery AJAX request does. Angular, instead, sends the data as a JSON-encoded string as part of the request stream.

You need to read in the data string from the input stream, and JSON decode it to be able to access it. You can read in the input stream like this, taken from here

request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(request.InputStream))
{
  return inputStream.ReadToEnd();
}

I'm not too familiar with asp.net, but here's an example in PHP that might illustrate the difference. When POSTing using jQuery, I can get username like this :

$username = $_POST['username']

But using Angular, it needs to be done like this :

$stream = file_get_contents("php://input"); // read input stream
$streamObj = json_decode($stream);  // json decode
$username = $streamObj->username;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.