首页 > 解决方案 > 如何让 Google Apps 脚本 doPost() 读取我的 POST 请求?

问题描述

我正在使用 node.js 和 Puppeteer 从无头浏览器运行一个抓取项目。我想将数据发布到 Google Apps 脚本以进行进一步处理。我希望在我的 GAS 项目中看到填充参数的数据。但相反,我得到以下结果,只有空参数。

https://script.googleusercontent.com/macros/echo?user_content_key=[key]

{"parameter":{},"contextPath":"","contentLength":-1,"queryString":"","parameters":{}}

这是生成该响应的 GAS 代码。

代码.gs
function doGet(e){
  return handleResponse(e);
}

function doPost(e){
  return handleResponse(e);
}

function handleResponse(e) {
  var json = JSON.stringify(e)
  var textOutput = ContentService.createTextOutput(json);
  return textOutput
}

这是我用来发送请求的代码。

刮刀.js
const request = require('request');
request({
  method: POST,
  preambleCRLF: true,
  postambleCRLF: true,
  uri: postUrl,
  multipart: {
    chunked: false,
    data,
  },
},

我已使用 [RequestBin][1] 验证我正在发送有效的 POST 请求。

我究竟做错了什么?

标签: javascriptnode.jspostgoogle-apps-script

解决方案


请查看您发布网络应用程序的方式。

  • 执行应用程序为:我
  • 谁有权访问该应用程序:任何人,甚至是匿名的

您的 POST 和 GET 的 URL 应该类似于https://script.google.com/macros/s/IDENTIFIER/exec,而不是https://script.googleusercontent.com/macros/echo?user_content_key=[key]。后一个 URL 看起来像是来自发布“任何人,甚至匿名”都无法访问的 Web 应用程序的重定向。

如果设置正确,此请求

curl --request POST \
  --url 'https://script.google.com/macros/s/IDENTIFIER/exec?param1=1&param2=2' \
  --header 'content-type: application/json' \
  --data '{"json": true}'

返回

{
  "parameter": {
    "param1": "1",
    "param2": "2"
  },
  "contextPath": "",
  "contentLength": 14,
  "queryString": "param1=1&param2=2",
  "parameters": {
    "param1": [
      "1"
    ],
    "param2": [
      "2"
    ]
  },
  "postData": {
    "type": "application/json",
    "length": 14,
    "contents": "{\"json\": true}",
    "name": "postData"
  }
}

推荐阅读