这个问题通常是由于传递给API网关的有效载荷不是有效的JSON格式而导致的。您可以通过在API网关的集成请求配置中将“Content-Type”设置为“application/json”来解决此问题。
下面是一个使用Node.js中的AWS SDK来创建API Gateway的示例代码,其中包含集成请求配置:
var AWS = require('aws-sdk');
AWS.config.update({region: 'us-west-2'});
var apigateway = new AWS.APIGateway({apiVersion: '2015-07-09'});
var params = {
restApiId: 'xxxxxxxxxx', // your API Gateway ID here
resourceId: 'xxxxxxxxxx', // your resource ID here
httpMethod: 'POST',
requestParameters: {
'method.request.header.Content-Type': true // enable the Content-Type header for the request
},
requestTemplates: {
'application/json': '{ "body" : $input.json("$") }' // transform the request body into a JSON object
},
passthroughBehavior: 'when_no_match',
type: 'AWS',
integrationHttpMethod: 'POST',
uri: 'arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:xxxxxxxxxxxx:function:myLambdaFunction/invocations', // your lambda function ARN here
credentials: 'arn:aws:iam::xxxxxxxxxxxx:role/lambda-role' // your lambda function IAM role ARN here
};
apigateway.putIntegration(params, function(err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
以上示例代码在API网关的集成请求配置中设置了“Content-Type”头和请求模板来确保传递给后端Lambda函数的有效载荷是有效的JSON格式。这应该能够解决“无法解析有效载荷为JSON”的问题。