Brandon Lee Brandon Lee - 1 month ago 10
Node.js Question

Express and Node, http call returns an array that is undefined when it's elements are called

I'm currently working my way through FreeCodeCamp's Back-End Development certification. I've gotten to the Image Search Abstraction microservice (link) and I'm using Node and Express for the backend code. I've made an http request to Google Custom Search api with the Request library and I'm able to make use of the returned data except for arrays of objects. The code I've written to put all the data into a returnable object is:

request(url,function(err,result,body) {
var images = [];
var data = JSON.parse(body);
data.items.forEach(function(val) {
var obj = {
image: val.pagemap.cse_image[0].src,
text: val.snippet,
source: val.link
}
images.push(obj);
})
res.send(images);


The issue I'm running into is the
val.pagemap.cse_image[0].src
. My localserver crashes when the request is made because:

image: typeof val.pagemap.cse_image[0],
^
TypeError: Cannot read property '0' of undefined


val.pagemap.cse_image
returns:

image: [
{
src: "http://i1.kym-cdn.com/photos/images/masonry/001/172/636/cfd.gif"
}
],


typeof val.pagemap.cse_image
returns 'object' and
Array.isArray(val.pagemap.cse_image)
returns true. But anything added to the end results in it return undefined. Even
.length
throws an undefined error.

Why is the array an array when it's called by itself but as soon as I try to try to call one if it's properties it's undefined?

Answer

If your val.pagemap.cse_image in fact contains this:

image: [
  {
    src: "http://i1.kym-cdn.com/photos/images/masonry/001/172/636/cfd.gif"
  }
],

then you need to instead access val.pagemap.cse_image.image[0].src.

Otherwise the problem may be that not all of your items' pagemap objects have a cse_image property.

Comments