Very Simple AngularJS $http POST Results in '400 (Bad Request)' and 'Invalid HTTP status code 400'

前端 未结 3 1585
有刺的猬
有刺的猬 2020-12-09 12:34

I have a very simple .NET Web API hosted in Azure, with two very simple methods:

[EnableCors(origins: \"http://simpleapiearl.azurewebsites.net\", headers: \"         


        
相关标签:
3条回答
  • 2020-12-09 12:49

    With AngularJS you can do in an easier way.

    You can inject $httpParamSerializer and then prepare your data through $httpParamSerializer(data).

    So your call should look something like:

    $http({
        method: 'POST',
        url: 'http://simpleApiEarl.azurewebsites.net/api/envelopes',
        data: $httpParamSerializer(env),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
      })
    
    0 讨论(0)
  • 2020-12-09 12:58

    I found a blog post that corrected my issue:

    http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

    Thanks to everyone for helping me out!

    0 讨论(0)
  • 2020-12-09 13:02

    I think this post would be helpful.

    How do I POST urlencoded form data with $http in AngularJS?

    By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

    This is the modified plnkr from yours. Your code is missing conversion of JSON to encoded url.

    http://plnkr.co/edit/4aeEDz73qgHSfOv1sBgn?p=preview

    $http({
        method: 'POST',
        url: 'http://simpleApiEarl.azurewebsites.net/api/envelopes',
        data: env,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function(obj) {
          var str = [];
          for(var p in obj)
          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
          return str.join("&");
        }
      }).
    
    0 讨论(0)
提交回复
热议问题