Http POST request body: Easy parameter extraction for application/x-www-form-urlencoded?

It’s really easy to access HTTP GET query parameters on the agent side via req.query.
It’s much harder to access the POST parameters when processing an application/x-www-form-urlencoded POST. They’re just in the req.body.

Does the “http” object provide any querystring -> JSON (or table) conversion functions?

For example when using jQuery to POST like this from a web page:


$.ajax({
      type: 'POST', 
      url: 'https://agent.electricimp.com/myagentid/setTheme',
      processData: false,
      data: { 'theme' : THEME, 'brightness' : BRIGHTNESS },
      success: function(dataString) {
          var data = $.parseJSON(dataString);
          console.log(dataString);
      }
});

On the agent (squirrel) side:


http.onrequest(function(req, resp) {
  server.log(req.body);
  // req.body = "theme=foobar&brightness=100"
  // req.query = { }
});

Are there any methods available to allow parsing such an “x-www-form-urlencoded” request body into a more convenient squirrel table (perhaps http.deparam(string))? Alternately, would it make sense to put these into req.query, for such POST requests?

I worked around this by sending the request body as a JSON string. The jQuery POST’s data parameter was modified like this:

data: JSON.stringify( {'theme': THEME, 'brightness':BRIGHTNESS})

Then, on the squirrel side in the request handler:

local params = http.jsondecode(req.body);  server.log(params.brightness);

The call you want is http.urldecode().

Peter

slaps forehead

Yes, indeed. I didn’t RTFM carefully enough, thank you for pointing that out.