为什么angular仍然将请求编码为JSON? ($ http,$ httpParamSerializerJQLike) [英] Why angular still encode request as JSON? ( $http, $httpParamSerializerJQLike )

查看:491
本文介绍了为什么angular仍然将请求编码为JSON? ($ http,$ httpParamSerializerJQLike)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望角色能够 x-www-form-urlencoded 默认情况下 。不是JSON。

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

angular 1.4.5

angular 1.4.5

这不起作用。

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

即使我在以下后添加:

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

但是当我在发出请求时直接在服务/控制器中使用它时起作用。
as:

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

如何配置整个应用程序使用x-www-form-urlencoded不带自行车 $ .param 拦截器等。

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

推荐答案

defaults.paramSerializer 仅用于URL构建,而不是 POST 正文, defaults.transformRequest 就是你所要的寻找

defaults.paramSerializer only used by URL building, not the POST body, the defaults.transformRequest is what you're looking for

这篇关于为什么angular仍然将请求编码为JSON? ($ http,$ httpParamSerializerJQLike)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆