Node-fetch POST request in Zapier fails with 'body used already for' error

I’m having trouble with a POST request in Zapier using node-fetch. Here’s my code:

fetchData('https://api.example.com', { 
  method: 'POST', 
  body: dataToSend 
})
.then(response => {
  console.log(response.text());
  return response.text();
})
.then(textData => {
  let result = { success: true, data: textData };
  finishTask(null, result);
})
.catch(finishTask);

When I run this, I get a red error message saying:

Error: body used already for: https://api.example.com

What does this mean? How can I fix it? I’m pretty new to using fetch in Zapier and I’m not sure what I’m doing wrong. Any help would be great!

I’ve encountered this issue before when working with node-fetch in Zapier. The error you’re seeing typically occurs because you’re trying to read the response body twice. In your code, you’re calling response.text() twice - once in the console.log and again in the return statement.

To fix this, you should only consume the response body once. Here’s how I’d modify your code:

fetchData('https://api.example.com', { 
  method: 'POST', 
  body: dataToSend 
})
.then(response => response.text())
.then(textData => {
  console.log(textData);
  let result = { success: true, data: textData };
  finishTask(null, result);
})
.catch(finishTask);

This way, you’re only calling response.text() once, which should resolve the ‘body used already’ error. Remember, the response body can only be read once, so always store it if you need to use it multiple times. Hope this helps!

The error you’re encountering is indeed related to consuming the response body multiple times. Node-fetch’s response body is a one-time use stream, which means once you’ve read it, you can’t read it again.

A simple fix would be to store the response text in a variable before using it. Here’s how you could modify your code:

fetchData('https://api.example.com', { 
  method: 'POST', 
  body: dataToSend 
})
.then(response => response.text())
.then(textData => {
  console.log(textData);
  return { success: true, data: textData };
})
.then(result => {
  finishTask(null, result);
})
.catch(finishTask);

This approach ensures you’re only reading the response body once, avoiding the ‘body used already’ error. It’s a common pitfall when working with fetch, especially if you’re coming from other HTTP libraries that allow multiple reads of the response body.

hey emma, ive seen that error too. the fix is to call response.text() only once. try storing it in a var like:

fetchData(url, { method: 'POST', body: data })
  .then(res => res.text())
  .then(txt => { console.log(txt); finishTask(null, { success: true, data: txt }); })
  .catch(finishTask);

hope it helps!