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

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);
};

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

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

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\"}"
}

Perfect, that worked.

Thanks for your time.

It’s annoying to have data.json body as a string, so I did this in the code:
const requestBody = typeof event.body === “string” ? JSON.parse(event.body) : event.body