5

I've a simply loop in node.js:

exports.sample = function (req, res) {
    var images = req.query.images;
    images.forEach(function (img) {
        console.log(img);
        console.log(img.path, img.id);
        console.log(img);
    });
    res.end();
};

The result is:

{"id":42,"path":"gGGfNIMGFK95mxQ66SfAHtYm.jpg"}
undefined undefined
{"id":42,"path":"gGGfNIMGFK95mxQ66SfAHtYm.jpg"}

I can access the properties in the client side but not on the server side.

Can someone help me to understand what's happening? Why can't I access my object properties?

4
  • 4
    Just check whether it is object or string Commented Jul 6, 2016 at 9:45
  • 1
    parse it maybe ? Commented Jul 6, 2016 at 9:45
  • 1
    add img = JSON.parse(img) before logs Commented Jul 6, 2016 at 9:45
  • 1
    The above comments are most likely correct. If img were an object then the console output would be more like Object {id: 42, path: "gGGfNIMGFK95mxQ66SfAHtYm.jpg"}. What you've posted is a string. Commented Jul 6, 2016 at 9:50

1 Answer 1

6

As others have pointed out, most probably img is in string form. You need to run JSON.parse() on it to convert it to an object, so you can access its properties.

Here I have written the JSON.parse() inside a check i.e. only when img is of type "string" should you parse it. But I think, you will always be getting img as a string, so you can simply parse it without the check.

exports.sample = function (req, res) {
    var images = req.query.images;
    images.forEach(function (img) {
        console.log(img);

        //Here, this code parses the string as an object
        if( typeof img === "string" )
          img = JSON.parse( img );

        console.log(img.path, img.id);
        console.log(img);
    });
    res.end();
};
Sign up to request clarification or add additional context in comments.

3 Comments

@belyid You were getting a string and not an object ( not arrays ) ;)
@belyid if you are working with express you should add body.parser as a middlware so you dont need to write this on every request.
In this case I was getting an array with only one string. But it could be more than one string that needed to be parsed.

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.