Brandon Lee Brandon Lee - 1 year ago 70
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,

The issue I'm running into is the
. My localserver crashes when the request is made because:

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


image: [
src: ""

typeof val.pagemap.cse_image
returns 'object' and
returns true. But anything added to the end results in it return undefined. Even
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 Source

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

image: [
    src: ""

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download