简体   繁体   中英

Why angular still encode request as JSON? ( $http, $httpParamSerializerJQLike )

I want to angular to make x-www-form-urlencoded requests by default . Not JSON.

angular 1.4.5

This doesnt work.

 angular.module('APP').config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
        $httpProvider.defaults.headers.post['Content-Type'] =  'application/x-www-form-urlencoded';
        $httpProvider.defaults.paramSerializer = '$httpParamSerializerJQLike';
    }]);

even when I add this after:

angular.module('APP').run(['$http', '$httpParamSerializerJQLike', function($http, $httpParamSerializerJQLike) {
  $http.defaults.paramSerializer = $httpParamSerializerJQLike;
}]);

But works when i use it directly in service/controller when making requests. as:

$http.post('/auth', $httpParamSerializerJQLike({email: email, pwd: pwd}))
.then(...

Now i use This interceptor: (bad code, wrond way, but works as I want)

angular.module('APP').factory('ApiInterceptor', ['$q', '$httpParamSerializerJQLike',
function($q, $httpParamSerializerJQLike){
  return {
    request: function (config) {
      $rootScope.loading = true;
      if (config.method === "POST"){
        if (config.data === undefined) config.data = {};
        config.data = $httpParamSerializerJQLike(config.data);
      }
      return config || $q.when(config);
    }
  };
}]);

How can i configure whole app to use x-www-form-urlencoded without bicycles as $.param interceptors etc.

defaults.paramSerializer只用于URL构建,而不是POST主体, defaults.transformRequest是你要找的东西

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM