首页 > 解决方案 > 将 Tsheets api 连接到 Google 应用脚本时出错

问题描述

从 GAS 环境运行以下脚本时,我收到错误消息:“属性提供的值无效:标头:主机”

function fetch() {var settings = {
    "async": true,
    "crossDomain": true,
    "method": "GET",
    "headers": {
      "Authorization": "Bearer "+token,
      "User-Agent": "PostmanRuntime/7.20.1",
      "Accept": "*/*",
      "Cache-Control": "no-cache",
      "Postman-Token": postman_token,
      "Host": "rest.tsheets.com",
      "Accept-Encoding": "gzip, deflate",
      "Connection": "keep-alive",
      "cache-control": "no-cache"
    }
  }
  var now = new Date();
  var day = now.getDate()>9? now.getDate():'0'+now.getDate();
  var date = now.getFullYear()+'-'+now.getMonth()+'-'+day;
  
  var url = organization+'/timesheets?start_date='+date;
  Logger.log(url);
  var response = UrlFetchApp.fetch(url,settings);
  Logger.log(response);
}

原始代码是使用 Postman 生成的,可以正常工作,但我将它从 AJAX 语法翻译成 GAS,但它在 GAS 环境中不起作用。

标签: javascriptgoogle-apps-script

解决方案


从标题字段中删除Host,它会自动指定,并且从 Apps 脚本中获取将不允许您指定它,只需将其删除,因为它是导致错误的原因。

关于其余的:

Postman-token在这里没用,你也可以删除它。与 相同user-agent,我相信它会被覆盖,因此可以安全地忽略它。

最后,参数 ascrossDomainasync虽然不会引发任何异常,但它们也会被忽略,因此您可以直接抑制它们。

这里,您将找到有关 的允许参数的文档Class UrlFetchApp,在这里您将找到有关标头字段定义的 w3c 文档。

这应该这样做:

var settings = {
    "method": "GET",
    "headers": {
      "Authorization": "Bearer "+token,
      "Accept": "*/*",
      "Cache-Control": "no-cache",
      "Accept-Encoding": "gzip, deflate",
      "Connection": "keep-alive",
      "cache-control": "no-cache"
    }


推荐阅读