我试图从 Angular 发送一个 json 结构到休息服务,做这样的事情
let test5var = {
"test5var1": {
"test5var2": "0317",
"test5var3": "9556"
},
"test5var4": "123",
"test5var": "0000046"
}
let dataPrincipalBlnc = {"test": {"test1": {"test2": "0317","test3": {"IDIOMA_ISO": " en","DIALECTO_ISO": "US"},"channel": "INT"},"input": {"test5": test5var}}};
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
let params = new HttpParams().set("requestData", dataPrincipalBlnc.toString()).set("authenticationType", this.authType);
return this.http.get(this.url, {params: params});
请求的结果应该如下所示:
但它目前发送为:
https://example.com/test?requestData=%5Bobject%20Object%5D&authenticationType=cookie
关于如何将 json 对象作为第一个请求发送给 looks 的任何想法?我需要手动将 json 转换为有效的 uri 格式吗?
在 angularJS 中,只需使用以下代码即可正常工作:
var data = {
"test1": {
"test2": {
"test3": "0317",
"test4": {
"IDIOMA_ISO": " en",
"DIALECTO_ISO": "US"
},
"channel": "INT"
},
"input": {
"test5": test5var
}
}
};
$http.get(url, {
params: {
authenticationType: authType,
requestData: data
}
}).then(success(deferred), error(deferred));
我也尝试过使用以下代码,但结果是添加了更多字符并且后端失败,因为它说 JSON 的格式无效:
encodeURIComponent(JSON.stringify(dataPrincipalBlnc)
?requestData=%257B%2522test%2522%253A%257B%2522test1%2522%253A%257B%2522test2%2522%253A%25220317%2522%252C%2522test3%2522%253A%257B%2522IDIOMA_2%2%535 %2522%2520en%2522%252C%2522DIALECTO_ISO%2522%253A%2522US%2522%257D%252C%2522channel%2522%253A%2522INT%2522%257D%252C%2522input%2522%253A%222%B%252%2522%253A%257B%252 %257B%2522test5var1%2522%253A%257B%2522test5var2%2522%253A%25220317%2522%252C%2522test5var4%2522%253A%25229556%2522%257D%252C%2522test5var4%2522%253A%2522123%2522%252C%2522test5var5 %2522%253A%25220003303%2522%257D%257D%257D%257D&authenticationType=cookie
谢谢 问候
最佳答案
传递给服务的任何 JSON 对象都应通过响应主体发送。 您应该只在 url 中添加有效的字符串参数。
还有url size limitation对于大多数浏览器,更大的对象可能会导致长 url 问题。
您看到的是 requestData=%5Bobject%20Object%5D&authenticationType=cookie
,因为它无法将 JSON 对象放入 url 查询字符串。
Some characters cannot be part of a URL (for example, the space) and some other characters have a special meaning in a URL: for example, the character # can be used to further specify a subsection (or fragment) of a document; the character = is used to separate a name from a value. A query string may need to be converted to satisfy these constraints. This can be done using a schema known as URL encoding.
当您有一个 JavaScript 对象并希望将其转换为字符串(包含 JSON 文本)时,请使用 JSON.stringify
。这称为序列化。
不考虑 JSON:
每当您想在 URL 中发送“有问题的”字符时,例如 &、% 等,请使用 encodeURIComponent
。相反的是 decodeURIComponent
。
我仍然希望在请求正文中发送对象。
所以在你的情况下使用:
let params = new HttpParams()
.set("requestData", encodeURIComponent(JSON.stringify(dataPrincipalBlnc)))
.set("authenticationType", this.authType);
关于json - Angular 7 HTTP GET 发送 JSON 对象作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54205182/