微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Google Apps Script UrlFetchApp GET 到 node.js 端点导致空正文

如何解决Google Apps Script UrlFetchApp GET 到 node.js 端点导致空正文

我正在使用 Google Apps 脚本对 node.js API 端点进行 UrlFetchApp 调用。我拥有 Google Apps 脚本代码和 node.js 代码和端点,所以我可以观察正在发生的事情。

当我使用 Postman 时,它可以工作。但是当我使用 GAS UrlFetchApp 时,它不起作用,因为节点中的 req.body 为空 { }。我什至查看了 Postman 为 JavaScript Fetch 创建的代码并尝试几乎复制它,除了我知道 GAS 的 UrlFetchApp 需要的东西。我已经使用 GAS 对各种外部端点进行了多次 UrlFetchApp 调用。所以,我不是新手,但无法弄清楚这一点。

这是我的 Google Apps 脚本代码

    var url = 'https://xxxxxxxxxxx.azurewebsites.net/api/account';

    var data = {
      "email": address,"apiKey": 'xxxxxxxxxxxxxxxxxxx'
    }

    var payLoadInfo = JSON.stringify(data);

    var options = {
      "method": "GET","headers": {'Content-Type': 'application/json'},// 'Content-Type': 'application/json',// "contentType": 'application/json',redirect: 'follow',"muteHttpExceptions": true,"body": payLoadInfo,// "payload": JSON.stringify(data)
      // payload: payLoadInfo
    };

    var response = UrlFetchApp.fetch(url,options);

“选项”中注释掉的部分是我尝试让它工作的几种不同方式。我知道过去我通常像这次一样使用“有效载荷”而不是“身体”(邮递员建议)。当我使用“有效负载”时,它完全失败,甚至无法访问我的节点代码。我也尝试将 apiKey 放在标题中。

这是 node.js API 端点代码

  router.get("/account",async (req,res) => {

  var apiKey = process.env.API_KEY;

  console.log('apiKey = ' + apiKey);
  console.log('req.body = ' + JSON.stringify(req.body,null,2));
  console.log('req.body.apiKey = ' + req.body.apiKey);

  if (req.body.apiKey != apiKey) {

    console.log('apiKey is not equal');
    res.status(401).send({ error: "You are not authorized." });

  } else {

    process the request...

  }

当我在“选项”中使用“有效负载”时,我得到 500,并且服务器代码永远不会执行。 当我在“选项”中使用“body”时,我看到服务器代码执行,但是 console.log('req.body = ' + JSON.stringify(req.body,2)),只是返回一个空对象 {},然后因为 req.body.apiKey != apiKey,它控制台“apiKey 不等于”并发送 401。使用 Postman 时,req.body 对象控制台很好,显示电子邮件和 apiKey。>

无论我将什么组合放入选项中,它都会以 500 或 401 失败。但是,Postman 在使用几乎相同的参数、标题等时效果很好。

以下是 Postman 显示代码

var myHeaders = new Headers();
myHeaders.append("Content-Type","application/json");
myHeaders.append("Cookie","ARRAffinity=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; ARRAffinitySameSite=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

var raw = JSON.stringify({"email":"xxxxxxxxxxxxxxxxx@gmail.com","apiKey":"xxxxxxxxxxxxxxxx"});

var requestOptions = {
  method: 'GET',headers: myHeaders,body: raw,redirect: 'follow'
};

我什至尝试包含 cookie 和“重定向:关注”,但都不起作用。

我错过了什么?

解决方法

感谢@Tanaike 的帮助(见上面的评论),我让它开始工作了。

似乎与 node.js 中的正常“获取”不同,Google Apps 脚本中的 URLFetchApp 不会随 GET 一起发送正文。

我仍然使用 GET,但改为发送 URL 中的 param 和 header 中的 apiKey。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。