如何编码特殊字符而不导致httpclient角度错误

问题描述 投票:0回答:1

我有一个数据id值STUDENT/STUD01,然后我尝试对

"/"
进行编码,但如果未编码,它会在httpclient中导致错误,它将创建一个新路径。

我尝试的是使用

encodeURI(data.id)
encodeURIComponent(data.id)

    const data = cloneDeep(this.form);
let url = this.getAPI();
url += `/${encodeURI(data.id)}`

    this.http.post(url, data).subscribe((.) => {....});

const data = cloneDeep(this.form); let url = this.getAPI(); url += `/${encodeURIComponent(data.id)}`

this.http.post(url, data).subscribe((.) => {....});

但是它会导致错误

Request URL: https://localhot:8080/api/list/STUDENT%STUD01  Referrer Policy: strict-origin-when-cross-origin
enter image description here

angular typescript httpclient
1个回答
0
投票

您可以尝试在正斜杠处拆分 ID,使用encodeURIComponent() 分别对每个部分进行编码,然后使用正斜杠将编码的部分重新连接在一起,如下所示:

    const data = cloneDeep(this.form);
    let url = this.getAPI();
    
    const encodedId = data.id.split('/').map(part => encodeURIComponent(part)).join('/');
    
    url += `/${encodedId}`;
    
    this.http.post(url, data).subscribe((response) => {.....});
© www.soinside.com 2019 - 2024. All rights reserved.