如何在 Angular 7 中编码包含特殊字符的查询参数? [英] How to encode query params containing special characters in Angular 7?
问题描述
我正在尝试在 Angular 7 中对查询参数值进行编码.但是当我的查询参数值包含任何特殊字符时,我得到 400 Bad Request 状态代码
失败的请求网址:http://localhost/api/67/cardvalues?parentcardvalues=STONE&parentcardvalues=STONE%20AGE
但是,当我的查询参数值不包含任何特殊字符时,我得到 200 OK 状态代码.
成功的请求网址:http://localhost/api/67/cardvalues?parentcardvalues=STONE&parentcardvalues=STONE
预期的请求 url 必须是这样的http://localhost/cardvalues?parentcardvalues=VALUE1&parentcardvalues=VALUE2
下面是我的代码,
parentcardvalues=["STONE","STONE AGE"]让 myparams = new HttpParams();if(parentcardvalues.length != 0)parentcardvalues.forEach((value) => {myparams = myparams.append('parentcardvalues', encodeURIComponent(value));});this.http.get(this.baseUrl + 'api/67/cardvalues', {params: myparams});
Swagger 规范是,
卷曲
curl -X GET "http://localhost/api/cardvalues?parentcardvalues=STONE&parentcardvalues=STONE%20AGE" -H "accept: application/json"
请求网址
http://localhost/api/cardvalues?parentcardvalues=STONE&parentcardvalues=STONE%20AGE
您可以使用以下方法解码您的参数:
decodeURIComponent(encodedURI_string)
更多信息这里>
I am trying to encode query parameter values in Angular 7. But I get 400 Bad Request status code, when my query parameter values contain any special character
Failed Request URL: http://localhost/api/67/cardvalues?parentcardvalues=STONE&parentcardvalues=STONE%20AGE
However, I get 200 OK status code , when my query parameter values do not contain any special characters.
Successful Request URL: http://localhost/api/67/cardvalues?parentcardvalues=STONE&parentcardvalues=STONE
The expected request url has to be like http://localhost/cardvalues?parentcardvalues=VALUE1&parentcardvalues=VALUE2
Below is my code,
parentcardvalues=["STONE","STONE AGE"]
let myparams = new HttpParams();
if(parentcardvalues.length != 0)
parentcardvalues.forEach((value) => {
myparams = myparams.append( 'parentcardvalues', encodeURIComponent(value) );
});
this.http.get(this.baseUrl + 'api/67/cardvalues', {params: myparams});
The Swagger specification is,
Curl
curl -X GET "http://localhost/api/cardvalues?parentcardvalues=STONE&parentcardvalues=STONE%20AGE" -H "accept: application/json"
Request URL
http://localhost/api/cardvalues?parentcardvalues=STONE&parentcardvalues=STONE%20AGE
you can decode your params using:
decodeURIComponent(encodedURI_string)
more information here
这篇关于如何在 Angular 7 中编码包含特殊字符的查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!