George Edwards George Edwards - 2 months ago 6
Node.js Question

Accessing GET response body parameters

I am using the

request
package to make a simple HTTP GET request to the npm API. I am trying to get the download counts for npm packages from an arbitrary function in my nodeJS backend.

Here is my updateDownloadCount.ts file:

export function updateDownloads() {
plugin.find(function (err, plugins: Array<any>) {
for (let plugin of plugins) {
var url = 'https://api.npmjs.org/downloads/point/last-month/' + plugin.package;

request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
})
}
})
}


So that's fine and I get a string of outputs like:

{"downloads":17627637,"start":"2016-08-29","end":"2016-09-27","package":"request"}


however, when I try to access just the
downloads
count, i.e.

console.log(body.downloads);


I get
undefined
console logged... How can I access the body variables? I feel like this should be super simple, but I couldn't find any docs on it.

Answer

Try to parse body if it is string type

export function updateDownloads() {
  plugin.find(function(err, plugins: Array < any > ) {
    for (let plugin of plugins) {
      var url = 'https://api.npmjs.org/downloads/point/last-month/' + plugin.package;

      request(url, function(error, response, body) {
        if (!error && response.statusCode == 200) {
          if (body && typeof body == "string") {
            body = JSON.parse(body);
          }
          console.log(body.downloads);
        }
      })
    }
  })
}
Comments