5

I'm using node-fetch to send some json data to an IFTTT restpoint. The data is successfully sent to the endpoint, but I'm getting an error in my NodeJS console. As you can see, it returns undefined then says there was an invalid json response body. I inspected the body and it looks fine to me.

What is the problem?

  async function checkTemperatureRange() {
    try {
      const temperatureSettings = await getTemperatureSetting();
      const currentTemperature = await getCurrentTemperature();

      if (currentTemperature < temperatureSettings.min_temp || currentTemperature > temperatureSettings.max_temp) {
        console.log('Temp NOT in range!');
        const body = { value1: currentTemperature };
        fetch('https://maker.ifttt.com/trigger/temp_reading/with/key/abc123', {
          method: 'post',
          body:    JSON.stringify(body),
          headers: { 'Content-Type': 'application/json' },
        })
        .then(function (res) {
          res.json()
        })
        .then(function (json) {
          console.log(json)
        })
        .catch(function (err) {
          console.log('node-fetch error: ', err)
        });
      }
      else {
        console.log('Temp in range :)');
      }
    } catch(error) {
      console.error(error);
    } 
  }

Error

undefined

(node:7488) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at https://maker.ifttt.com/trigger/temp_reading/with/key/abc123 reason: Unexpected token C in JSON at position 0
    at C:\Users\leke\dev\code-training-camp-demo\node_modules\node-fetch\lib\index.js:272:32
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
(node:7488) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:7488) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Edit

If I console.log(res) I get

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]:
   { body:
      PassThrough {
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: true,
        _transformState: [Object] },
     disturbed: false,
     error: null },
  [Symbol(Response internals)]:
   { url: 'https://maker.ifttt.com/trigger/temp_reading/with/key/abc123',
     status: 400,
     statusText: 'Bad Request',
     headers: Headers { [Symbol(map)]: [Object] },
     counter: 0 } }

So is it to do with the Bad request?

user126440
  • 391
  • 1
  • 2
  • 19
  • Instead of `JSON.stringify(body)` as body pass straightly `body` – Subburaj Oct 14 '19 at 10:08
  • I got a similar error, with the difference being `reason: Unexpected token B in JSON at position 0` – user126440 Oct 14 '19 at 10:13
  • Curious though, Why are you chaining promise in async function? – Alwaysblue Oct 14 '19 at 10:18
  • Also see if this might be useful: https://stackoverflow.com/questions/29775797/fetch-post-json-data – Alwaysblue Oct 14 '19 at 10:20
  • 1
    The response is not JSON, you are receiving a plain text answer : https://maker.ifttt.com/trigger/temp_reading/with/key/TlHVR3IcWdjG4jWroMYC- returns `Congratulations! You've fired the temp_reading event`. By the way, you should disable that token – Seblor Oct 14 '19 at 10:29
  • Ok, thanks. So it's not important it returns json then. Thank's for the token warning too ;) – user126440 Oct 14 '19 at 10:34
  • That's an internal response generated by the fetch component when no response body is provided back to you from the server responding to your REST call. – Mike Kormendy Sep 22 '20 at 16:43

1 Answers1

11

Whoops, I forgot the return, and also IFTTT returns text(), not json.

.then(function (res) {
  return res.text();
})
user126440
  • 391
  • 1
  • 2
  • 19
  • Hey!, thanks your answer helped me fix my problem, My response was returning an empty object until I used res.text(). could you be so kind to explain hy does this work?, I though the POST methods returned a JSON type response. Thank you. – Kay Feb 01 '21 at 15:33
  • 1
    @Kay I think it depends on the endpoint and what it's returning. I'm working on a project where the API-endpoint allows me to specify the format in the query `?format=json` – idkwhatsgoingon Apr 22 '21 at 12:17