angularjsapiangularjs-http

How to POST content as application/x-www-form-urlencoded


angularjs $http.post is refusing to use my Content-Type

I am working with a contractor - their team are making server-side APIs while I'm putting together a javascript application using angularjs. They insist on making the api only allow calls with application/x-www-form-urlencoded calls, so I'm trying to figure out how to use $http to make a urlencoded call, and running into problems. All the instruction pages I'm finding seem focused on older versions of angularjs.

I try using the below code:

$scope.makeApiCall = function(  ){
    var apiData = {
                    "key1" : "value1",
                    "key2" : "value2"
                };
    var apiConfig = {
                    "headers" : {
                        "Content-Type" : "application/x-www-form-urlencoded;charset=utf-8;"
                    }
                };
    return $http.post('/Plugins/apiCall', apiData, apiConfig)
    .then(function(response){
        $scope.data=response.data;
    });
};

But when I make the call, instead of using the Content-Type I provided, the developer tools report that it uses Content-Type: text/html; charset=utf-8

How do I get my $http.post to send the right Content-Type?


Solution

  • How to POST content as application/x-www-form-urlencoded

    Use the $httpParamSerializerJQLike service to transform the data:

    .controller(function($http, $httpParamSerializerJQLike) {
      //...
    
      $http({
        url: myUrl,
        method: 'POST',
        data: $httpParamSerializerJQLike(myData),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });
    
    });
    

    For more information, see