首页 > 解决方案 > 通过 zapier 代码发布到 API 并收到此错误

问题描述

我正在尝试通过 Zapier 代码向我正在使用的 API 运行 JSON 帖子。

我已经定义了我的输入,这是我下面的代码。它似乎可以通过大部分内容而没有任何语法错误。但是 Zapier 现在给了我这个错误响应,我不知道为什么?

“我们在发送您的测试时遇到问题。请再试一次。错误:您必须返回单个对象或对象数组。”

有人对此有任何意见吗?

const API_URL = "https://myapi.com";

const DATA = {
  siteId: "xxxx",
  id: inputData.orderId,
  totalATI: 39.99,
  totalET: 39.99,
  currency: "USD",
  accountId: inputData.accountId,
  ip: inputData.userIP,
  recoverUrl: "",
  civility: "",
  lastname: inputData.lastname,
  firstname: inputData.firstname,
  email: inputData.accountId,
  homePhoneNumber: "",
  mobilePhoneNumber: "",
  phoneNumber: inputData.userPhone,
  countryCode: "01",
  custom:{},
  
  items: [{
  id: "88",
  label: "CR",
  quantity: 1,
  totalATI: 39.99,
  totalET: 39.99,
  url: "https://myurl.com",
  imageUrl: "https://myimage.com",
  universe: "",
  category:  ""
  }]
};

fetch(API_URL, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'X-API-Key': 'xxx'
  },
  body: JSON.stringify(DATA)
}).then(function(res){
  return res.json();
}).then(function(response){
  // API response
  if(response.success){
    // Tell zapier success
    callback(null, {
      result: "success",
      message: "Request successful!",
      data: response
    });
  }
  // Some error happened.
 else {callback(response)};

}).catch(callback);

标签: javascriptarraysjsonjavascript-objectszapier

解决方案


我相信这里发生的事情是来自 API 的响应不是正确的 JSON,这就是对 API 进行调用但fetch库无法解析响应的原因。

例如,这段代码是解析一个 JSON 响应。

fetch(API_URL, {
    method: 'POST',
    body: JSON.stringify(DATA),
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'X-API-Key': 'xxx'
    }
})
    .then(function(res) {
        return res.json();
    })
    .then(function(body) {
        console.log(body);
        callback(null, body.json);
    }).catch(callback);

当响应不是正确的 JSON 时,此代码将出错。

您可以尝试将您的代码更改为以下您正在考虑以文本形式进行响应的代码。

fetch(API_URL, {
    method: 'POST',
    body: JSON.stringify(DATA),
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'X-API-Key': 'xxx'
    }
})
    .then(function(res) {
        return res.text();
    })
    .then(function(body) {
        console.log(body);
        var output = {rawHTML: body};
        callback(null, output);
    })
    .catch(callback);

我在这里发布了类似的答案。


推荐阅读