How to read the POST parameters in a serverless application with Lambda?

raphadko picture raphadko · Mar 15, 2018 · Viewed 7.5k times · Source

I'm submitting a form to a Lambda function deployed by serverless, here's the yml:

functions:
  hello:
    handler: handler.hello
    events:
      - http: POST hello

Now my hello function is:

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Se222rverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };

  callback(null, response);
};

I can see on the output that the variables were passed, but they are stored in the event.body property as such:

 "body":"email=test%40test.com&password=test12345"

Now I can access this string, but I can't read individual variables from it, unless I do some regex transformation which, I believe, would not be the case in such a modern stack such as serverless/aws.

What am I missing? How do I read the individual variables?

Answer

bdh picture bdh · Mar 17, 2018

It looks like your Serverless endpoint is receiving data with Content-Type: application/x-www-form-urlencoded. You could update the request to use JSON data instead to access the post variables the same way you would other JavaScript objects.

Assuming this isn't an option; you could still access your post body data using the node querystring module to parse the body of the request, here is an example:

const querystring = require('querystring');

module.exports.hello = (event, context, callback) => {

  // Parse the post body
  const data = querystring.parse(event.body);

  // Access variables from body
  const email = data.email;

  ...

}

Just remember if some of the parameters in the post body use names that are invalid JavaScript object identifiers to use the square bracket notation, e.g.:

const rawMessage = data['raw-message'];