I wish to convert a JS object into x-www-form-urlencoded. How can I achieve this in angular 2?
export class Compentency {
competencies : number[];
}
postData() {
let array = [1, 2, 3];
this.comp.competencies = array;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers, method: 'post' });
return this.http.post(this.postUrl, JSON.stringify(this.comp), options)
.map(res => res.json().data.competencies)
.catch(this.handleError);
}
To use the x-www-form-urlencoded type in Postman, we need to select the radio button with the same name within the request's body tab. As already mentioned, the request consists of the key-value pairs. Postman will encode the data before sending it to the server. Additionally, it will encode both the key and the value.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
let o = { a:1, b:'2', c:true };
let s = new URLSearchParams(Object.entries(o)).toString();
console.log(s);
Assume have an object named postdata as below:
const postdata = {
'a':1,
'b':2,
'c':3
};
and, you want convert it into x-www-form-urlencoded format, like: a=1&b=2&c=3
with URLSearchParams it's very easy to do it.
const rawData = new URLSearchParams(Object.keys(postdata).map(key=>[key,postdata[key]]));
console.log(rawData.toString());//a=1&b=2&c=3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With