Tuesday 14 March 2017

Parsing URL-encoded request body in Google Cloud Functions

I have a HTTP function that responds to GET requests by displaying an HTML form, and I'd like to respond to POST requests from that form. Unfortunately, it looks like Cloud Functions don't support application/x-www-form-urlencoded request bodies.

exports.setup = function setup(req, resp) {
  if (req.method == 'GET') {
    // Display a form for the user. The form POSTs to this function.
    resp.send(`
<form enctype="application/x-www-form-urlencoded" method="POST">
  <input id="foo"></input>
  <button>Submit</button>
</form>`);
  } else if (req.method == 'POST') {
    console.log('got req.body:', req.body);
    resp.send(req.body);
  }
};

In this example, the log says

got req.body: {}

And the browser displays an empty page.

This SO answer suggests that I should app.use(bodyParser.urlencoded({extended: true})); but it's unclear how to use that app variable with GCF.



via Jason Hall

No comments:

Post a Comment