'Convert encoded application/x-www-form-urlencoded post data to json object
A client wants to be able to make xmlhttp ajax requests with the default content type of content-type:"application/x-www-form-urlencoded; charset=UTF-8" but sending the data in the form the API expects application/json. So the request comes across as this:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:80/api/metadata/taxonomy",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
},
"processData": false,
"data": "{\n\t\"practice\": [\"Learning\"]\n}"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
But the API expects to be able to get req.body as a JSON object it can immediately use:
"{"practice":["Learning"]}"
Can I transform this "{\n\t\"practice\": [\"Learning\"]\n}" to this "{"practice":["Learning"]}" in some safe/suggested manner? (without some home grown parsing function or regex)
Solution 1:[1]
You can actually post JSON as body.
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:80/api/metadata/taxonomy",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
},
"dataType" : "json"
"processData": false,
"data": { "practice": ["Learning"] }
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Notice that theirs a new property which tells that data type to be posted is JSON and and now in data property the value is in JSON format instead of string.
Hope this solves your problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anand Siddharth |
