AWS CDK目前不支持在API Gateway集成响应定义中直接设置Content-Type。但是,我们可以通过在Lambda函数中手动设置响应头来达到相同的效果。以下是一个示例Lambda函数,它返回JSON响应并设置Content-Type头:
import { APIGatewayProxyHandler } from 'aws-lambda';
export const handler: APIGatewayProxyHandler = async (event) => {
const responseBody = {
message: "Hello, world!"
};
return {
statusCode: 200,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(responseBody)
};
};
在CDK中,我们可以使用lambdaIntegration
帮助程序包装Lambda函数,并将其集成到API Gateway中:
import * as apigw from '@aws-cdk/aws-apigateway';
import * as lambda from '@aws-cdk/aws-lambda';
// Define the Lambda function
const handler = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
code: lambda.Code.fromAsset('path/to/my/function/code'),
handler: 'index.handler',
});
// Create the API Gateway REST API
const restApi = new apigw.RestApi(this, 'MyRestApi');
// Define the API Gateway integration for the Lambda function
const lambdaIntegration = new apigw.LambdaIntegration(handler);
// Define the API Gateway resource for our endpoint
const resource = restApi.root.addResource('hello');
// Define the API Gateway method for our endpoint
resource.addMethod('GET', lambdaIntegration, {
// Define any API Gateway method options, such as request / response parameters
// ...
});
// Set the API Gateway deployment options, such as stage name and description
// ...
通过这种方法,我们可以手动设置Lambda函数的响应头,并将其与API Gateway集成。