0

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"
        }
    ]
}
1
  • 1
    I don't understand. Your code does resolve(JSON.parse(returnData)); which attempts to parse the data you received and change if FROM JSON into a Javascript object. So, if the code does what it is designed to do, this function returns a promse that resolves to a Javascript object, not JSON. If you want JSON as the resolved value and the http request is retrieving JSON, then don't parse it before calling resolve(), just return the JSON. Commented Jul 20, 2019 at 14:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.