This might be a n00b question, but I am trying to understand nodeJS code that is given to me which supposedly works in production. This is an API which I want to make use of, but stuck as it fails to understand the JSON string that comes in the request.
var server = {};
server.create = function _create(req) {
//req= JSON.parse(req);
req.forEach(function (origReq) {
console.log(origReq);
});
}
var req = "[{\"id\":\"1\"},{\"id\":\"2\"}]";
server.create(req);
Running this, I get this error because "req" is not identified as a JS object/array and the .forEach is not available on a string, which it is:
**
TypeError: undefined is not a function
**
Understandably, if the "Commented" line of code is uncommented, the string is parsed to proper JS array and it works Ok.
With the request having a proper content-type of "application/json", is it not understood/parsed by default? how possibly the code without the parse statement could work (parse statement was introduced by me and does not exist in the original code part of a working API). Probably the node module (server module as it is usually called) should handle this from the incoming header info?
My apologies if I am missing something fundamental and thanks for all your inputs.
req.bodytoserver.create()? Who knows. The only way it could have possibly worked before is if it was passed an already parsed array.