admin 管理员组文章数量: 1086019
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?
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?
Share Improve this question asked Jul 6, 2016 at 9:43 belyidbelyid 8712 gold badges12 silver badges29 bronze badges 4-
4
Just check whether it is
object
orstring
– Rayon Commented Jul 6, 2016 at 9:45 - 1 parse it maybe ? – elreeda Commented Jul 6, 2016 at 9:45
-
1
add
img = JSON.parse(img)
before logs – imkost Commented Jul 6, 2016 at 9:45 -
1
The above ments are most likely correct. If
img
were an object then the console output would be more likeObject {id: 42, path: "gGGfNIMGFK95mxQ66SfAHtYm.jpg"}
. What you've posted is a string. – Reinstate Monica Cellio Commented Jul 6, 2016 at 9:50
1 Answer
Reset to default 6As 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();
};
本文标签: nodejsWhy can39t I access object properties in javascriptStack Overflow
版权声明:本文标题:node.js - Why can't I access object properties in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744057774a2526162.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论