Accessing event.body in serverless create --template hello-world

#1

Hello, I have created the template hello-world using serverless create --template hello-world

I then run it serverless invoke local --function submit --path data.json

data.json is a valid JSON. I access the data with

let data = event.body this works when running locally. However it does not work when running in Lamda and sending a application/json body.

After some reading I have come to the conlusion that I require a BodyParser and I am to somehow add that into my function. However everything I read assumes I have access to app

Like this app.use(bodyParser.json({ strict: false }))

However at least in this template there is no app

Any clues, thanks!

cat handler.js 
'use strict';

module.exports.helloWorld = (event, context, callback) => {
  console.log(JSON.parse(event.body));
  const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*', // Required for CORS support to work
    },
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };

  callback(null, response);
};
#2

Hi, what error did you get? How do you work with event.body?

#3

Hey,

So I think its down to me having to JSON.parse(event.body)); when it’s in Lambda, but in local event.body is already a JS object.

So local I get the error Unexpected token o in JSON at position 1

#4

Yep, you are right - you need to use JSON.parse. As for invoke local - you just need to save your event body as JSON.stringify((JSON.stringify(body)). So instead of

{
  "body": { "key": "value"}
}

you will have a data.json

{
"body": "{\"key\":\"value\"}"
}
#5

Perfect, that worked.

Thanks for your time.