简体   繁体   中英

AWS Lambda trying to write event.body to Aurora DB throws error

I have a table in Aurora DB. I am trying AWS API Gateway, AWS Lambda and AWS Aurora DB.

I created a Lambda function which does receive request from API Gateway and triggers the handler function but it does not write the event.body to the table.

exports.insertBill = function(event, context, callback) {


     context.callbackWaitsForEmptyEventLoop = false;

     console.log(event.body);

     var query = rDBConnection.query('INSERT INTO Bill SET ?', event.body, function(err, result) {
        if (err) {
           callback(null, {"statusCode": 400, "body": JSON.stringify(err)});

        } else {
        var recordId = result.insertId;
         console.log("Record ID " + recordId);
         var result = {recordId};
         callback(null, {"statusCode": 200, "body": JSON.stringify(result)});
       }
      });



  }

the code does connect to DB. When I try setting the body as follows (from Lambda Test Interface)

  "body": "{\n     \"vendor_Id\" : 101,\n  \"user_Id\"  :  2224\n  \n }",

it does display the body as (from console.log) :

{
     "vendor_Id" : 101,
  "user_Id"  :  2224

 }

but throws an SQL error :

{
  "statusCode": 400,
  "body": "{\"code\":\"ER_PARSE_ERROR\",\"errno\":1064,\"sqlState\":\"42000\",\"index\":0}"
}

when I try hard coded value like { "vendor_Id" : 101, "user_Id" : 2224 } in rDBConnection.query instead of event.body --> in that case the code writes a DB record .

I am not sure what I am missing here. I receive similar results while testing from API Gateway Test Interface.

I figured out. The API Gateway sends to Lambda the body as JSON string so I did JSON.parse on the body before writing to the db.

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-input-format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM