Home node js receives wrong data from angular PUT call

# node js receives wrong data from angular PUT call

user10738
1#
user10738 Published in September 19, 2018, 7:14 pm

I'm implementing a rest-crud client in angular that sends data to a node api ( that I'm implementing as well )

When I try to send data from the form->angular to the node api with ngResource like so

  cmsApp.factory('Misc', ['$resource', function($resource) {
return $resource('/api/misc/:id', {}, { 'update': { method:'PUT' } // the$resource obj comes with save/query/get/delete but lacks the update-put method
});
}]);


therefore I get an error

  Error: invalid json


now, I found a workaround following this (old) article

 cmsApp.config(function ($httpProvider) {$httpProvider.defaults.transformRequest = function (data) {
var str = [];
for (var p in data) {
data[p] !== undefined && str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p]));
}
return str.join('&');
};
$httpProvider.defaults.headers.put['Content-Type'] =$httpProvider.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded; charset=UTF-8';
});


this trick kinda works but breaks all the strings in an array, so for example if I have a string like

 "foo bar"


what I get on the other side is

  {
'0': 'f',
'1': 'o',
'2': 'o',
'3': ' ',
'4': 'b',
'5': 'a',
'6': 'r'
}


that is clearly like unusable data.

I'd like to know the proper way to make this work, or if are any other correct pattern around, to make this right.

APPENDIX A

    router.route('/misc/:misctype')
.put(function(req, res) {
console.log(req.body.text_label);
});

• This is a classic example of the XY Problem. meta.stackexchange.com/questions/66377/what-is-the-xy-problem. It would be better to show the receiving server code and preferably the original JSON that is coming Invalid, rather than try to figure out why some other workaround isn't exactly right. – Claies Oct 31 '14 at 19:59
• I we got the classic example of td;rd (urbandictionary.com/define.php?term=tl%3Bdr) + "I think I know what's going on" here, fwiw I've embedded the code of the receiver – holographix Oct 31 '14 at 20:23
• I read the whole document; You stated that you received "Error: invalid json", so you tried to implement a workaround you read somewhere which only partially solved the issue. The thing is, if you included not just the receiving code but the actual output that was wrong, we could probably discover why it's coming across invalid without even needing to deal with that workaround that clearly was not written for your scenario to begin with. – Claies Oct 31 '14 at 23:48
• The point is there isn't any reason why the first bit of code you posted would throw any error requiring a workaround, unless there is something else happening, and solving that is what you really want to accomplish. – Claies Oct 31 '14 at 23:52