Search code examples
node.jslambdakong

Kong service with POST request to Lambda function and JSON payload


I'm just starting with Kong and setup a Lambda plugin on a service to try things out. The Lambda function I use had a simple method to parse the JSON body:

const getBody = (event: any): IBody => {
  const body = JSON.parse(event.body)
  return new Body(body)
}

So, although I was able to call the function and get a response from it, all I got was an error message similar to:

{"status":500,"message":"SyntaxError: Unexpected token u in JSON at position 0"}


Solution

  • This is due the fact a Lambda request is different when invoked from the cli and when called from AWS API Gateway.

    Basically event.body is only available when calling from the API Gateway, whilst when called from the cli, the correct property name is event.request_body.

    So modifiying the method to the one below will allow me to receive calls both from AWS API Gateway and cli:

    const getBody = (event: any): IBody => {
      const body = JSON.parse(Object.is(event.request_body, undefined) ? event.body : event.request_body)
      return new Body(body)
    }