通过浏览器访问时仅记录 Google Web 应用程序

问题描述 投票:0回答:1

我的 Google 网络应用程序遇到一个奇怪的问题:

function doGet(e) {
  Logger.log("GET");
  Logger.log(JSON.stringify(e))
  return HtmlService.createHtmlOutput('<h1>Thanks for using Apps Scripts</h1>');
}
function doPost(e) {
  Logger.log("POST");
  Logger.log(JSON.stringify(e))
  return HtmlService.createHtmlOutput('<h1>Thanks for using Apps Scripts</h1>');
}

该应用程序是开放的,因此每个人都可以访问它。当我将 URL 粘贴到(私有)窗口中时,它始终按预期工作,

doGet
被调用,并且我在执行选项卡中看到日志。但是,当我通过浏览器控制台中的 Fetch API 或 Postman 或 Klavio 等服务访问相同的 URL 时,有时看不到日志:

有些行不可扩展,因此不显示任何内容。更准确地说,Postman 和 Klavio post 请求从未起作用,而当从与 Apps 脚本页面相同的选项卡中的浏览器控制台发送时,Fetch API 请求(GET 和 POST)起作用。可能与 CORS 有关吗?但是我不会看到错误,而不是完成状态吗? Postman 请求也返回状态 200 并且没有显示错误。

但是它说函数

doGet
已执行(并完成),当我发送post请求时,它会按预期执行
doPost
。它如何在不记录任何内容的情况下执行我的函数?

google-apps-script post cors
1个回答
0
投票

当您通过浏览器登录Google帐户访问Web Apps时,可以记录

Logger.log
的日志。但是,当您在浏览器上使用脚本、curl、postman、Javascript等访问Web Apps时,似乎存在通过
Logger.log
console.log
记录日志的规则。在这种情况下,我认为我的报告可能会有用。我从未在 Stackoverflow 上发布过它。所以,我想把它放在这个答案中。

为了测试这一点,有以下 3 个步骤。

1. Web 应用程序的示例脚本

这是一个用于检查日志的示例脚本。

const doGet = (e) => {
  Logger.log(`GET method: ${JSON.stringify(e)}`);
  console.log(`GET method: ${JSON.stringify(e)}`);
  return ContentService.createTextOutput(
    JSON.stringify({ method: "GET", e: e })
  );
};
const doPost = (e) => {
  Logger.log(`POST method: ${JSON.stringify(e)}`);
  console.log(`POST method: ${JSON.stringify(e)}`);
  return ContentService.createTextOutput(
    JSON.stringify({ method: "POST", e: e })
  );
};
  • 此 Web 应用程序部署为
    Execute the app as: Me
    Who has access to the app: Anyone

2. Google Apps 脚本项目示例

本次测试准备了2种类型的Google Apps Script项目。

  1. 独立类型的 Google Apps 脚本 WITHOUT 链接 Google Cloud Platform (GCP) 项目

    • 在这种情况下,您可以通过直接创建来检索此独立的 Google Apps 脚本。
  2. 独立类型的 Google Apps 脚本WITH链接 Google Cloud Platform (GCP) 项目

    • 在这种情况下,您可以通过 此流程检索此独立的 Google Apps 脚本。

3.测试
Logger.log
console.log

对于上述

doGet
doPost
的Web应用程序,它请求以下4种模式。

  1. 对于

    doGet

    $ curl -L "https://script.google.com/macros/s/###/exec"
    
  2. 对于

    doPost

    $ curl -L -d "key=value" "https://script.google.com/macros/s/###/exec"
    
  3. 对于

    doGet
    。使用访问令牌。

    $ curl -L -H "Authorization: Bearer ###" "https://script.google.com/macros/s/###/exec"
    
  4. 对于

    doPost
    。使用访问令牌。

    $ curl -L -H "Authorization: Bearer ###" -d "key=value" "https://script.google.com/macros/s/###/exec"
    

结果与讨论

可以确认日志的条件如下。

没有访问令牌 带有访问令牌
未链接 GCP 应用程序脚本仪表板
链接GCP 堆栈驱动程序 Apps 脚本仪表板和 Stackdriver

根据以上结果,发现如下。

  • 使用默认 Google Apps 脚本项目而不链接到 Google Cloud Platform (GCP) 时,需要使用访问令牌访问 Web Apps 才能检索请求的日志,即使部署设置为

    Execute the app as: Me
    Who has access to the app: Anyone

  • 使用链接到 GCP 的 Google Apps 脚本项目时,您可以从 Stackdriver 检索 Web Apps 的所有用户访问日志,无论

    Execute the app as: Me
    Who has access to the app: Anyone
    等部署设置如何。

参考文献

© www.soinside.com 2019 - 2024. All rights reserved.