简体   繁体   中英

Execution failed due to configuration error: Malformed Lambda proxy response in Node JS Lambda

This is Node JS Lambda, I am returning status code 200 as the response, when i call my lambda function through api gateway, i am getting 502 error, i am sending post request to my API Gateway URL. I am using Lambda proxy api integration.

      request( options, function ( error, res, body ) {
            if ( error ) {
                console.log( "this is error", error );
                return callback( error );
            } else {
                // console.dir( body );
                const response = {
                    statusCode: 200,
                    body: JSON.stringify({
                      message: 'Your function executed successfully!',
                    //   input: event,
                    }),
                  };
                return callback( null, {
                    response,
                } );
            }
        } );

I am Seeing this is the logs

(543396a4-952b-451e-8e61-6aeedd2463e9) Endpoint response body before transformations: 
{
    "response": {
    "statusCode": 200,
    "body": "{\"message\":\"Your function executed successfully!\"}"
}
}
 (543396a4-952b-451e-8e61-6aeedd2463e9) Execution failed due to configuration error: 
 Malformed Lambda proxy response
 (543396a4-952b-451e-8e61-6aeedd2463e9) Method completed with status: 502

It's a bit unintuitive, but the response needs to have a couple of additional properties, and the json payload needs to be a bit more well-formed.

The final response will be:

return {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Origin": "*", // or add a specific site (can only provide one origin, not multiple)
            "Content-Type": "application/json" // must include the content type
        },
        isBase64Encoded: false, // not necessarily required, but good practice
        body: JSON.stringify({
            "message": "Your function executed successfully!"
        })
    }

Notice:

  • json quotes on the property name
  • json no longer has a dangling comma
  • Content-Type is added in the header

The key takeaway here is the body for a json response for the body must be properly formed and stringified.

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