gpt4 book ai didi

angular - 内容类型 `application/x-www-form-urlencoded` 的编码对象

转载 作者:搜寻专家 更新时间:2023-10-30 21:56:01 26 4
gpt4 key购买 nike

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

最佳答案

I have created this formatData() function which tries to serialize the data, but it just doesn't work 100% of the time. Specifically when there is nested JSON data.

如果您必须使用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

关于angular - 内容类型 `application/x-www-form-urlencoded` 的编码对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56223414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com