google-apps-script - Google Apps 脚本 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,并且服务器代码永远不会执行。当我在“选项”中使用“正文”时,我看到服务器代码执行,但是 console.log('req.body = ' + JSON.stringify(req.body, null, 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 中的参数和标头中的 apiKey。
推荐阅读
- sql - 将大表导入Sqlite时如何避免磁盘节流?
- selenium - PDF 验证,不仅仅是文本,还有字体和页脚/页眉大小
- javascript - Map 方法返回未定义的值
- javascript - Chrome 扩展脚本有时会在网页之前加载
- node.js - Express App 提供不需要的静态文件
- wolfram-mathematica - 制作一个不在原点的半球
- java - 如何将 Java 比较器序列化为 JSON?
- docker - 将样式添加到正在运行的 OpenMapTiles 服务器
- python - 带拉链的循环
- regex - 带有断言运算符的 Ansible 正则表达式