繁体   English   中英

如何在 Google Cloud Function 中获取原始请求正文?

[英]How can I get the raw request body in a Google Cloud Function?

我需要原始请求正文能够对其进行 SHA-1 消化以验证 Facebook webhook X-Hub-Signature 标头,该标头与请求一起传递给我的 Firebase 函数(在 Google Cloud Functions 上运行)。

问题是,在这种情况下(使用Content-Type: application/json标头)GCF 使用bodyParser.json()自动解析主体,该主体使用来自流的数据(意味着它不能在 Express 中间件链中再次使用) 并且只提供解析后的 javascript 对象作为req.body 原始请求缓冲区被丢弃。

我试图为functions.https.onRequest()提供一个 Express 应用程序,但这似乎是作为一个子应用程序运行的,或者是请求正文已经被解析的东西,就像你将一个普通的请求响应回调传递给onRequest() .

有什么方法可以禁用 GCF 为我解析正文? 或者我可以以某种方式指定我自己的verify回调bodyParser.json()吗? 或者有其他方法吗?

PS:一周前我第一次就此事联系了 Firebase 支持,但由于缺乏回应,我现在在这里尝试。

现在您可以从req.rawBody获取原始主体。 它返回Buffer 有关更多详细信息,请参阅文档

感谢 Nobuhito Kurose 在评论中发布此内容。

不幸的是,默认中间件目前无法获取原始请求正文。 请参阅:在 HTTP 函数中访问未解析的 JSON 正文 (#36252545)

 const escapeHtml = require('escape-html');

/**
 * Responds to an HTTP request using data from the request body parsed according
 * to the "content-type" header.
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */
exports.helloContent = (req, res) => {
  let name;

  switch (req.get('content-type')) {
    // '{"name":"John"}'
    case 'application/json':
      ({name} = req.body);
      break;

    // 'John', stored in a Buffer
    case 'application/octet-stream':
      name = req.body.toString(); // Convert buffer to a string
      break;

    // 'John'
    case 'text/plain':
      name = req.body;
      break;

    // 'name=John' in the body of a POST request (not the URL)
    case 'application/x-www-form-urlencoded':
      ({name} = req.body);
      break;
  }

  res.status(200).send(`Hello ${escapeHtml(name || 'World')}!`);
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM