notyourguru
notyourguru

Reputation: 43

How to return JSON using node or Express

My http get request is returning [object][object]. How do I stringify my request so that it returns the data in proper json?

function httpGet() {
    return new Promise(((resolve, reject) => {
        var options = {
            host: 'api.airtable.com',
            port: 443,
            path: '/v0/app000000000/Database?filterByFormula=(DrugName=%27azatadine%27)',
            method: 'GET',
            headers: {
                'Authorization': 'Bearer key12345677890'
            }
        };
        const request = https.request(options, (response) => {
            response.setEncoding('utf8');
            let returnData = '';

            response.on('data', (chunk) => {
              returnData += chunk;
            });

            response.on('end', () => {
              resolve(JSON.parse(returnData));
            });

            response.on('error', (error) => {
              reject(error);
            });
          });
          request.end();   
    }));
}

I would like to return the Indication in a record such as the get response below:

    "records": [
        {
            "id": "recBgV3VDiJeMkcwo",
            "fields": {
                "DrugName": "azatadine",
                "nameapi": [
                    "recBgV3VDiJeMkcwo"
                ],
                "Indication": "For the relief of the symptoms of upper respiratory mucosal congestion in perennial and allergic rhinitis, and for the relief of nasal congestion and eustachian t.b. congestion.",
                "lookup": [
                    "azatadine"
                ],
                "drugID": "recBgV3VDiJeMkcwo"
            },
            "createdTime": "2018-11-09T19:38:24.000Z"
        }
    ]
}

Upvotes: 0

Views: 51

Answers (1)

Rico Chen
Rico Chen

Reputation: 2298

Take out JSON.parse from response.on('end') callback and you should be good. Reason being returnData is JSON formatted, parsing it will return the JS object representation but what you want is the JSON string.

Upvotes: 2

Related Questions