Renuka Prasad A
Renuka Prasad A

Reputation: 107

unable to access json data of imgur api

I'am trying to access image search results from imgur api,while i get the response for the image which is in the format

{
"data":[...images...],
"success":true,
"status":200
}

i get undefined value when i try to access data key from api response

var express = require('express');

var app = express()

// node module to get api data
var request = require('request')


app.get('/searchimage/:value', function (req, res) {

            var options = {
                url: 'https://api.imgur.com/3/gallery/search/1?q=dragon',
                headers: {
                    Authorization: "Client-ID ae63041e2274e37"
                }
            }

            request(options, function (request, resp, body) {
                // outputs undefined
                console.log(body["data"])
                // outputs undefined
                console.log(body.data)
                // outputs data as described in the above response format
                console.log(body)

                res.send(body)

            })

        })

any hint at where i'am making a mistake?

Upvotes: 0

Views: 360

Answers (1)

ufxmeng
ufxmeng

Reputation: 2600

The body you got is just a JSON string, so it has no property named data. Use JSON.parse to convert JSON string to the corresponding Object.

console.log(JSON.parse(body).data)

Upvotes: 1

Related Questions