节点api请求返回数组,但在尝试使用索引时出错

时间:2016-11-01 16:54:29

标签: javascript node.js shopify

在节点中发出get请求时,尝试从数组返回索引值时遇到问题。这是使用shopify模块,但我相信这将适用于所有获取请求。 我的职责是:

ShopifyObj.Shopify.get('/admin/products.json',  function(err, data, headers){
  console.log(data.products[0]);      
});

以上回报:

“的console.log(data.products [0]);
TypeError:无法读取未定义“

的属性”0“

然而;当我尝试没有索引的console.log时,我得到一个数组:

ShopifyObj.Shopify.get('/admin/products.json',  function(err, data, headers){
  console.log(data.products);      
});

//returns
 [ { id: 6560603013,
title: 'Dog',
body_html: 'A cute dog',
vendor: 'Test store 1994 1994',
product_type: '',
created_at: '2016-10-27T11:11:32-04:00',
handle: 'dog',
updated_at: '2016-10-27T11:11:33-04:00',
published_at: '2016-10-27T11:11:00-04:00',
template_suffix: null,
published_scope: 'global',
tags: '',
variants: [ [Object] ],
options: [ [Object] ],
images: [ [Object] ],
image:
 { id: 16395126725,
   product_id: 6560603013,
   position: 1,
   created_at: '2016-10-27T11:11:33-04:00',
   updated_at: '2016-10-27T11:11:33-04:00',
   src: 'https://cdn.shopify.com/s/files/1/1569/4167/products/imagejpeg_0_5.jpg?v=1477581093',
   variant_ids: [] } },
  { id: 6560596805,
title: 'Long sleeve tshirt',
body_html: 'Super long sleeves',
vendor: 'Test store 1994 1994',
product_type: '',
created_at: '2016-10-27T11:10:45-04:00',
handle: 'long-sleeve-tshirt',
updated_at: '2016-10-27T11:13:56-04:00',
published_at: '2016-10-27T11:10:00-04:00',
template_suffix: null,
published_scope: 'global',
tags: 'dog, short-sleeve-t-shirt',
variants: [ [Object] ],
options: [ [Object] ],
images: [ [Object] ],
image:
 { id: 16395113157,
   product_id: 6560596805,
   position: 1,
   created_at: '2016-10-27T11:10:47-04:00',
   updated_at: '2016-10-27T11:10:47-04:00',
   src: 'https://cdn.shopify.com/s/files/1/1569/4167/products/profilepic.jpg?v=1477581047',
   variant_ids: [] } },
  { id: 6560275461,
title: 'Short Sleeve T-Shirt',
body_html: 'A nice t-shirt',
vendor: 'Test store 1994 1994',
product_type: '',
created_at: '2016-10-27T10:38:58-04:00',
handle: 'short-sleeve-t-shirt',
updated_at: '2016-10-27T10:38:59-04:00',
published_at: '2016-10-27T10:38:00-04:00',
template_suffix: null,
published_scope: 'global',
tags: '',
variants: [ [Object] ],
options: [ [Object] ],
images: [ [Object] ],
image:
 { id: 16394553413,
   product_id: 6560275461,
   position: 1,
   created_at: '2016-10-27T10:38:59-04:00',
   updated_at: '2016-10-27T10:38:59-04:00',
   src: 'https://cdn.shopify.com/s/files/1/1569/4167/products/World-Wide-Web.jpg?v=1477579139',
   variant_ids: [] } } ]

我觉得我在异步方面做错了但我无法弄明白。当console.log的settimeout()几秒钟时,它将正确显示。有没有办法得到我想要的结果而不必在任意时间内使用settimeout?

1 个答案:

答案 0 :(得分:0)

您收到的内容无疑是一个JSON字符串。 为了将数据用作数组对象,您需要先解析它。

var data = JSON.parse(data.products);
console.log(data[0]);