Vin*_*rma 8 encoding json typescript angular
我有一个 JSON 对象并使用 HttpParams 传递它,但它转换 + 到空间并发送到后端。我已经尝试了所有可能的方法,但没有人为 JSONObject 字符串解决了这个问题。
this.updateUser({"name":"ABC","mobile": "+911234567890","text":"1 + 2 = 3"});
public updateUser(myObj) {
const body = new HttpParams().set('user_object', JSON.stringify(myObj));
return this.http.post(url, body, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
});
}
Run Code Online (Sandbox Code Playgroud)
当我在 Network 中检查时,包含 + 字符的对象会自动转换为空格。
Jah*_*wal 17
这是角度的 HttpParams 的问题。的+
中的一个参数值被转换为一个。我有一个类似的问题,其中我有一个 POST 请求,它接受 Base64 编码字符串形式的文件。该文件的 Base64 转换可以包含一个
+
正在转换为. 我在我的项目中实现了一个 CustomURLEncoder 来处理相同的问题。以下是供您参考的片段:
import {HttpParameterCodec} from '@angular/common/http'
export class CustomURLEncoder implements HttpParameterCodec {
encodeKey(key: string): string {
return encodeURIComponent(key);
}
encodeValue(key: string): string {
return encodeURIComponent(key);
}
decodeKey(key: string): string {
return decodeURIComponent(key);
}
decodeValue(key: string) {
return decodeURIComponent(key);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将编码器与 HttpParams 一起使用,如下所示:
import {CustomURLEncoder} from './urlencoder.component';
import {HttpParams, HttpHeaders, HttpClient} from '@angular/common/http';
export class ApiService {
constructor(private httpClient: HttpClient){}
base64 = "Encoded+Base64+File+Data" //String with '+'
const fileDetails = new HttpParams({encoder: new CustomURLEncoder() })
.set('filename','CustomEncodedFile.xlsx')
.set('filedata',base64);
return this.httpClient.post(url, fileDetails, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-
form-urlencoded;charset=utf-8')
});
}
Run Code Online (Sandbox Code Playgroud)
这是一个常见问题。+
URL 使用该字符来分隔两个单词。为了+
在参数值中使用字符,您需要先对参数值进行编码,然后再将其添加为 URL 的一部分。Javascript / TypeScript 提供了encodeURI()
用于该特定目的的函数。
URL编码将字符转换成可以通过Internet传输的格式。[w3Schools 参考]
以下是解决此问题的方法:
let mobile = encodeURI("+911234567890");
let text = encodeURI("1 + 2 = 3");
this.updateUser({"name":"ABC","mobile": mobile,"text":text});
public updateUser(myObj) {
const body = new HttpParams().set('user_object', JSON.stringify(myObj));
return this.http.post(url, body, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
});
}
Run Code Online (Sandbox Code Playgroud)
或者
您可以在 updateUser() 方法内部进行编码:
this.updateUser({"name":"ABC","mobile": "+911234567890","text":"1 + 2 = 3"});
public updateUser(myObj) {
let encodedJson = encodeURI(JSON.stringify(myObj));
const body = new HttpParams().set('user_object', encodedJson);
return this.http.post(url, body, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
});
}
Run Code Online (Sandbox Code Playgroud)
或者
+
在发送到服务器之前使用正则表达式进行替换:
let jsonData = JSON.stringify(myObj);
jsonData = jsonData.replace(/\+/gi, '%2B');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6208 次 |
最近记录: |