简体   繁体   中英

How to write node-fetch (Rest-API) in “Code by Zapier”?

In zapier I use an action of Code By Zapier. It's based on node.js. I need to use fetch for implementing REST-API of my CRM.

Here is the code I wrote, which runs well when I tried it with VS Code (outside Zapier):

// the code by zapier includes already the require('fetch')

var api_token = "..."; // my api
var deal_name = "Example"; // a string

fetch("https://api.pipedrive.com/v1/deals/find?term="+deal_name+"&api_token=" + api_token)
  .then(function(res) {
    return res.json();
  }).then(function(json) {
     var deal_id = json.data[0].id;
     console.log("deal_id="+deal_id);
  }).catch(function(error) {
     console.log("error");
  });

output = {id: 1, hello: "world"}; // must include output...

The error I got from Zapier is:

If you are doing async (with fetch library) you need to use a callback!

Please help me with solving it.

Zapier knows, that fetch is a async function. You have to use the callback-function and not the output variable.

 // bad code fetch(url) .then(function(res) { return res.json(); }).then(function(json) { // when i run this in my node repl it works perfect! // the problem is this doesn't return the data to zapier // it just prints it to the system output console.log(json); }); // good code fetch(url) .then(function(res) { return res.json(); }).then(function(json) { // but if i swap this to callback, this works perfect in zapier callback(null, json); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM