0

I'm writing a Node.js server and I'm trying to fetch data from an API and return it to my user. I'm taking the insightlyResponse and trying to convert to JSON. Here's my code:

  insightlyResponse.setEncoding('utf8');
      let rawData = '';
    insightlyResponse.on('data', (chunk) => rawData += chunk);
    insightlyResponse.on('end', () => {
    try {
        const parsedData = JSON.parse(rawData);
        responseData = "PARSED";
    } catch (e) {
        responseData = `Got error: ${e.message}`
    }
  response.end(responseData);
  });

The error is Got error: Unexpected token \u001f in JSON at position 0. What does this mean and what am I doing wrong?

A Tyshka
  • 3,830
  • 7
  • 24
  • 46
  • "trying to convert to JSON" I think you mean "trying to convert _from_ JSON". What's in `rawData`? Presumably not JSON. – user94559 Sep 22 '17 at 19:01
  • @smarx I'm following this: https://stackoverflow.com/questions/11826384/calling-a-json-api-with-node-js – A Tyshka Sep 22 '17 at 19:29
  • If I don't parse and leave as is I get a bunch of gibberish, if I do parse I get an error. – A Tyshka Sep 22 '17 at 19:30
  • Why did you think that trying to parse "a bunch of gibberish" as though it were JSON would work? – user94559 Sep 22 '17 at 19:33
  • Step 1 will be figuring out what sort of data you actually have. (This probably involves reading documentation for the API you're calling or whatever `insightlyResponse` is.) Then figure out if you need to do something different to get JSON or if you need to learn how to parse the response you're already getting. – user94559 Sep 22 '17 at 19:34
  • @smarx This API documentation says it returns JSON. I ran AJAX off my browser and the API worked just fine, until they disabled CORS. – A Tyshka Sep 22 '17 at 19:39
  • I doubt others are going to be able to help you without knowing what API you're using, seeing how you're calling it, what type of thing `insightlyResponse` is, etc. So either you'll need to provide more information, or you'll need to do some debugging yourself (e.g. try calling a different API to make sure that part of your code works correctly, or try to identify what the "gibberish" actually is). – user94559 Sep 22 '17 at 19:44
  • @smarx The API is here if you'd like to see it: https://api.insight.ly/v2.2/Help#!/Contacts/GetContacts – A Tyshka Sep 22 '17 at 19:47

1 Answers1

0

Figured it out! I double-checked the API and realized that it can return compressed responses. Turned off that setting and works like a charm!

A Tyshka
  • 3,830
  • 7
  • 24
  • 46