Google Script UrlFetchApp“方法”:“删除”错误

时间:2017-10-04 21:24:21

标签: google-apps-script

我无法让这段代码工作,我相信它会在谷歌的最后,因为相同的代码在Netbeans IDE中完美运行。我也可以通过Google脚本PUTPOST获得相同的数据,但我无法DELETE。我担心虽然文档here表明UrlFetchApp能够删除,但它实际上可能无法实现或正在工作。我没有在网上找到使用"method":"delete" URLFetchApp的人的在线示例。有没有人能够进行删除工作,如果没有,您是否看到我的现有代码可以使PUTPOST工作而不是DELETE?谢谢!

var delete_options = {
     'method' : 'DELETE',
     'contentType': 'application/json',
     'payload' : JSON.stringify(modifySkillsForAgentsPayload),
     'headers' : {
       'Authorization' : 'bearer ' + accessToken,
       'Accept' : 'application/json'

     }
  };
  UrlFetchApp.fetch(url,delete_options);

2 个答案:

答案 0 :(得分:1)

您还可以尝试修改modifySkillsForAgentsPayload,使用encodeURIComponent对其进行编码,然后将其附加到URL。这对我有用!

这是我最终使用的代码:



// More information at http://apidocs.yotpo.com/reference#delete-a-purchase
function deleteYotpoOrder(order_id) {

  // Token retrieved from API
  var token = 'randomStringofLettersAndNumbers9cg078as-0345';

  var orders = encodeURIComponent('[{"order_id": "' + order_id + '"}]');

  //Set the method to GET, POST, or DELETE
  var params = {
    "method": "DELETE",
    'contentType': 'application/json'
    // Can't use paylad with "DELETE" method
    //'payload' : JSON.stringify(data),
  };

  var deleteFromYotpoURL = "https://api.yotpo.com/apps/YOUR_APP_KEY/purchases?utoken=" + token + "&orders=" + orders;

  try {
  
    var result = UrlFetchApp.fetch(deleteFromYotpoURL, params);
    var strFrmFbObj = result.getContentText();
    Logger.log("Result of Delete request: " + strFrmFbObj);

  } catch (e) {
    var errorSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Errors');
    var lastRow = errorSheet.getLastRow();
    var timestamp = new Date();
    var cell = errorSheet.getRange('A1');
    cell.offset(lastRow, 0).setValue(e.message);
    cell.offset(lastRow, 1).setValue(e.fileName);
    cell.offset(lastRow, 2).setValue(e.lineNumber);
    cell.offset(lastRow, 3).setValue(timestamp);
  }
}




答案 1 :(得分:0)

此代码适合您。

function test()
{
  var url = "https://jsonplaceholder.typicode.com/posts/1";

  var delete_options = {
    'method' : 'DELETE',
    'contentType': 'application/json',
    //      'payload' : JSON.stringify({"test":"test"}),
    'headers' : {
      'Authorization' : 'bearer ' + ScriptApp.getOAuthToken(),
      'Accept' : 'application/json'        
    }
  };

  var blob = UrlFetchApp.fetch(url, delete_options);
  Logger.log(blob);
}

原因,为什么你的代码不能正常工作,因为HTTP DELETE操作不应该有一个请求体。许多(或几乎所有)REST API都是以这种方式设计的。

虽然禁止在删除请求中发送请求正文。您可以阅读更多相关信息here