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

前端 未结 3 1888
广开言路
广开言路 2021-01-03 23:38

I need the raw request body to be able to SHA-1 digest it to validate the Facebook webhook X-Hub-Signature header that\'s passed along with the request to my Firebase Functi

相关标签:
3条回答
  • 2021-01-04 00:02

    Unfortunately the default middleware currently provides no way to get the raw request body. See: Access to unparsed JSON body in HTTP Functions (#36252545).

    0 讨论(0)
  • 2021-01-04 00:03
     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')}!`);
    };
    
    0 讨论(0)
  • 2021-01-04 00:07

    Now you can get the raw body from req.rawBody. It returns Buffer. See documentation for more details.

    Thanks to Nobuhito Kurose for posting this in comments.

    0 讨论(0)
提交回复
热议问题