SAM 本地启动 api CORS 问题

red*_* 87 6 javascript amazon-web-services node.js typescript

我正在使用 AWS CDK (Typescript) 并运行 SAM 本地启动 api 来启动与 lambda 解析器关联的 API,但在尝试从浏览器访问该 API 时遇到了 CORS 问题。这是我的代码:

拉姆达配置

import { Construct } from 'constructs';
import {
  IResource,
  LambdaIntegration,
  MockIntegration,
  PassthroughBehavior,
  RestApi,
} from 'aws-cdk-lib/aws-apigateway';
import {
  NodejsFunction,
  NodejsFunctionProps,
} from 'aws-cdk-lib/aws-lambda-nodejs';
import { Runtime } from 'aws-cdk-lib/aws-lambda';

import { join } from 'path';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as rds from 'aws-cdk-lib/aws-rds';
import * as cdk from 'aws-cdk-lib';

export function addCorsOptions(apiResource: IResource) {
  apiResource.addMethod(
    'OPTIONS',
    new MockIntegration({
      integrationResponses: [
        {
          statusCode: '200',
          responseParameters: {
            'method.response.header.Access-Control-Allow-Headers':
              "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'",
            'method.response.header.Access-Control-Allow-Origin': "'*'",
            'method.response.header.Access-Control-Allow-Credentials':
              "'false'",
            'method.response.header.Access-Control-Allow-Methods':
              "'OPTIONS,GET,PUT,POST,DELETE'",
          },
        },
      ],
      passthroughBehavior: PassthroughBehavior.NEVER,
      requestTemplates: {
        'application/json': '{"statusCode": 200}',
      },
    }),
    {
      methodResponses: [
        {
          statusCode: '200',
          responseParameters: {
            'method.response.header.Access-Control-Allow-Headers': true,
            'method.response.header.Access-Control-Allow-Methods': true,
            'method.response.header.Access-Control-Allow-Credentials': true,
            'method.response.header.Access-Control-Allow-Origin': true,
          },
        },
      ],
    }
  );
}

export class FrontendService extends Construct {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    const vpc = new ec2.Vpc(this, 'HospoFEVPC');
    const cluster = new rds.ServerlessCluster(this, 'AuroraHospoFECluster', {
      engine: rds.DatabaseClusterEngine.AURORA_POSTGRESQL,
      parameterGroup: rds.ParameterGroup.fromParameterGroupName(
        this,
        'ParameterGroup',
        'default.aurora-postgresql10'
      ),
      defaultDatabaseName: 'hospoFEDB',
      vpc,
      scaling: {
        autoPause: cdk.Duration.seconds(0),
      },
    });

    const bucket = new s3.Bucket(this, 'FrontendStore');

    const nodeJsFunctionProps: NodejsFunctionProps = {
      environment: {
        BUCKET: bucket.bucketName,
        CLUSTER_ARN: cluster.clusterArn,
        SECRET_ARN: cluster.secret?.secretArn || '',
        DB_NAME: 'hospoFEDB',
        AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
      },
      runtime: Runtime.NODEJS_14_X,
    };

    const registerLambda = new NodejsFunction(this, 'registerFunction', {
      entry: 'dist/lambda/register.js',
      memorySize: 1024,
      ...nodeJsFunctionProps,
    });

    const registerIntegration = new LambdaIntegration(registerLambda);

    const api = new RestApi(this, 'frontend-api', {
      restApiName: 'Frontend Service',
      description: 'This service serves the frontend.',
    });

    const registerResource = api.root.addResource('register');
    registerResource.addMethod('POST', registerIntegration);
    addCorsOptions(registerResource);
  }
}
Run Code Online (Sandbox Code Playgroud)

拉姆达旋转变压器

export async function handler(event: any, context: any) {
    return {
      statusCode: 200,
      headers: { 'Access-Control-Allow-Origin': '*' },
      body: JSON.stringify(body),
    };
}
Run Code Online (Sandbox Code Playgroud)

当我将该函数部署到 AWS 并尝试从实时 URL 访问端点时,它工作正常,没有任何 CORS 问题,因此看起来错误可能与 SAMS-CLI 有关。我该如何解决这个问题?

编辑

这是来自终端的图像,您可以在其中看到失败的OPTIONS请求。

在此输入图像描述

Reg*_*ole -2

根据此文档,您不需要手动配置飞行前 OPTIONS 方法。

例如,

new apigateway.RestApi(this, 'api', {
  defaultCorsPreflightOptions: {
    allowOrigins: apigateway.Cors.ALL_ORIGINS,
    allowMethods: apigateway.Cors.ALL_METHODS // this is also the default
  }
})
Run Code Online (Sandbox Code Playgroud)

然后你就可以取消手册了addCorsOptions()