Issue
Im having a JSON object and passing it using HttpParams but it coverts + to space and sent to backend. I have tried all possible ways but no one solved it for an JSONObject string.
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')
});
}
When I inspect in Network that object containing + character automatically converts into space.
Solution
This ia a common problem. The +
character is used by the URL to separate two words. In order to use the +
character in the parameter values, you need to encode your parameter values before adding them as part of the URL. Javascript / TypeScript provide a encodeURI()
function for that specific purpose.
URL encoding converts characters into a format that can be transmitted over the Internet. [w3Schools Reference]
Here is how you can fix this problem:
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')
});
}
OR
You can encode indside the updateUser() method:
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')
});
}
OR
Use a regular expression to replace +
before sending to the server:
let jsonData = JSON.stringify(myObj);
jsonData = jsonData.replace(/\+/gi, '%2B');
Answered By - Faisal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.