【问题标题】:Encoding objects for content-type `application/x-www-form-urlencoded`内容类型的编码对象`application/x-www-form-urlencoded`
【发布时间】:2019-05-21 04:12:09
【问题描述】:

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

【问题讨论】:

  • application/json 发送数据。不要打扰application/x-www-form-urlencoded
  • 如果必须使用application/x-www-form-urlencoded,请使用jQuery param对数据进行编码。
  • 是的,由于后端限制,我必须使用x-www-form-urlencoded。所以我正在尝试使用@angular/common/http 让它工作你能给我一个使用jQuery.param 转换一些嵌套JSON 的例子吗?
  • @georgeawg 请让 jQuery.param 评论成为答案。我会选择一个最佳答案。

标签: angular typescript ionic-framework


【解决方案1】:

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

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

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>

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

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

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

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 1970-01-01
    • 2015-04-02
    • 2022-11-21
    • 2019-09-12
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    相关资源
    最近更新 更多