0

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.

3
  • 2
    Perhaps someone was using Express with JSON parsing middleware and passed req.body to server.create()? Who knows. The only way it could have possibly worked before is if it was passed an already parsed array. Commented Jun 22, 2015 at 4:54
  • You should not call a JavaScript object/array a "JSON object/array". That's just confusing when actually talking about JSON as well. Commented Jun 22, 2015 at 4:56
  • @mscdex: Thanks and I get your point. It could no way be an already parsed array from the browser request and has to be parsed before being processed. I did not see Express or any middleware being used. However, I will be investigating more on this for sure Commented Jun 22, 2015 at 5:00

1 Answer 1

1

content-type "application/json" will not be retrieved as a JavaScript object. You are retrieving plain text (string). Just like "text/HTML" or "text/plain" content-types.

calling JSON.parse(req) is key as it will parse this string into a JavaScript object.

EDIT:

Some frameworks (like Angular.js) will read the response's content-type and parse the response into a JavaScript Object for you. However the "request" Node Module (that you might be using) will not parse the response for you. You must do it yourself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.