首页 > 解决方案 > 内容类型“application/x-www-form-urlencoded”的编码对象

问题描述

AngularJS 代码到 Angular 2+ 代码 - Http 问题

我正在将一些较旧的 AngularJS 代码(实际上是其 Ionic 1)转换为较新的 Angular(Ionic 4),我遇到了一个烦人的问题。

因此,在 AngularJS 中的每一个 Http Post 上,之前的开发者都是这样做的:

var headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
};

// Add authentication headers if required
if (token) headers['x-auth-token'] = token;
if (userid) headers['x-auth-id'] = userid;

var config = {
  url: api(endpoint),
  method: method,
  headers: headers
};

if (method == 'GET') {
  config['params'] = data;
} else {
  config['data'] = $httpParamSerializerJQLike(data);
}

return $http(config).then(function(response) {
  return response.data;
});

手头的问题是这一行:$httpParamSerializerJQLike(data);

在 Angular 2+ 中,这不存在并且会导致问题。

有人可以帮我将其转换为更新版本的 Angular 吗?

这是我到目前为止所拥有的:

let headers = {
  "Content-Type": "application/x-www-form-urlencoded"
};

if (this.token) headers["x-auth-token"] = this.token;
if (this.userid) headers["x-auth-id"] = this.userid.toString();

let config = {
  url: await this.api(endpoint),
  method: method,
  headers: headers,
  body: data
};

if (method === "GET") {
  config["params"] = data;
  return await this.http.get(config["url"], config).toPromise();
} else {
  config["data"] = await this.formatData(data);
  return await this.http
    .post(config["url"], config["data"], config)
    .toPromise();
}

如您所见,我创建了这个formatData()尝试序列化数据的函数,但它不能 100% 工作。特别是当有嵌套的 JSON 数据时。

这是我创建的 formatData 函数:

async formatData(obj) {
  var str = [];
  for (var key in obj) {
    if (obj != undefined) {
      if (obj.hasOwnProperty(key)) {
        str.push(
          encodeURIComponent(key) + "=" + encodeURIComponent(obj[key])
        );
      }
    }
  }
  return str.join("&");
}

任何帮助是极大的赞赏!如果有人知道我可以安装的任何库或与此库类似的任何内容:$httpParamSerializerJQLike(data);

标签: angulartypescriptionic-framework

解决方案


我创建了这个formatData()试图序列化数据的函数,但它不能 100% 工作。特别是当有嵌套的 JSON 数据时。

如果必须使用application/x-www-form-urlencoded,请使用jQuery 参数对数据进行编码。

console.log($.param({a:88, b:77}));
console.log($.param({a: {b:4,c:8}}));
console.log($.param({a: [4,8]}));
<script src="//unpkg.com/jquery"></script>

没有为内容类型编码 JavaScript 对象的正式标准application/x-www-form-urlencoded。jQuery 库将param函数推广为一种对对象和数组进行编码的方法。一些 API 将其理解为事实上的标准。

编码 JavaScript 对象和数组的正式标准是JSON.org,由 Douglas Crockford 推广并被公认为标准RFC8258和 ECMA-404。

如果可能,最好使用内容类型application/json


推荐阅读