【发布时间】:2019-12-30 11:47:08
【问题描述】:
我有一个示例模板,它正在创建一个 AWS Lambda 函数和一个 API 网关,
我面临的问题是模板能够启用 CORS,但这似乎是错误的,因为来自前端应用程序的调用仍会收到 CORS 错误。
下面是模板-
AWSTemplateFormatVersion: '2010-09-09'
Description: AWS API Gateway with a Lambda Integration
Parameters:
CorsOrigin:
Type: String
Default: "'*'"
CorsHeaders:
Type: String
Default: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
CorsMethods:
Type: String
Default: "'OPTIONS,POST'"
Resources:
BusinessLambda:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
def handler(event, context):
response = {
'isBase64Encoded': False,
'statusCode': 200,
'headers': {},
'multiValueHeaders': {},
'body': 'Hello, World!'
}
return response
Description: AWS Lambda function
FunctionName: 'businessLambda'
Handler: index.handler
MemorySize: 128
Role: 'arn:aws:iam::awsAccountId:role/service-role/TestRole'
Runtime: python3.7
Timeout: 15
ApiGatewayRestApi:
Type: AWS::ApiGateway::RestApi
Properties:
ApiKeySourceType: HEADER
Description: An API Gateway with a Lambda Integration
EndpointConfiguration:
Types:
- EDGE
Name: api-gw
ApiGatewayResource:
Type: AWS::ApiGateway::Resource
Properties:
ParentId: !GetAtt ApiGatewayRestApi.RootResourceId
PathPart: 'lambda'
RestApiId: !Ref ApiGatewayRestApi
ApiGatewayMethod:
Type: AWS::ApiGateway::Method
Properties:
ApiKeyRequired: false
AuthorizationType: NONE
HttpMethod: POST
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: "POST"
Uri: !Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${!stageVariables.lambdaAlias}/invocations'
IntegrationResponses:
- StatusCode: 200
ResponseTemplates:
application/json: $input.json('$')
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: !Ref CorsHeaders
method.response.header.Access-Control-Allow-Methods: !Ref CorsMethods
method.response.header.Access-Control-Allow-Origin: !Ref CorsOrigin
RequestTemplates:
application/json: $input.json('$')
MethodResponses:
- ResponseParameters:
method.response.header.Access-Control-Allow-Headers: true
method.response.header.Access-Control-Allow-Methods: true
method.response.header.Access-Control-Allow-Origin: true
StatusCode: '200'
OperationName: 'lambda'
ResourceId: !Ref ApiGatewayResource
RestApiId: !Ref ApiGatewayRestApi
APIGatewayOptionsMethod:
Type: "AWS::ApiGateway::Method"
Properties:
ResourceId: !Ref ApiGatewayResource
RestApiId: !Ref ApiGatewayRestApi
AuthorizationType: NONE
HttpMethod: OPTIONS
Integration:
Type: MOCK
IntegrationResponses:
- ResponseParameters:
method.response.header.Access-Control-Allow-Headers: !Ref CorsHeaders
method.response.header.Access-Control-Allow-Methods: !Ref CorsMethods
method.response.header.Access-Control-Allow-Origin: !Ref CorsOrigin
ResponseTemplates:
application/json: ''
StatusCode: '200'
PassthroughBehavior: WHEN_NO_MATCH
RequestTemplates:
application/json: '{"statusCode": 200}'
MethodResponses:
- ResponseModels:
application/json: 'Empty'
ResponseParameters:
method.response.header.Access-Control-Allow-Headers: false
method.response.header.Access-Control-Allow-Methods: false
method.response.header.Access-Control-Allow-Origin: false
StatusCode: '200'
ApiGatewayStage:
Type: AWS::ApiGateway::Stage
Properties:
DeploymentId: !Ref ApiGatewayDeployment
Description: API GW Stage dev
RestApiId: !Ref ApiGatewayRestApi
StageName: 'dev'
Variables:
'lambdaAlias' : 'businessLambda'
GWLambdaPermission:
Type: "AWS::Lambda::Permission"
Properties:
Action: "lambda:InvokeFunction"
FunctionName: !Ref BusinessLambda
Principal: "apigateway.amazonaws.com"
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ApiGatewayRestApi}/*/POST/lambda"
ApiGatewayDeployment:
Type: AWS::ApiGateway::Deployment
DependsOn: APIGatewayOptionsMethod
Properties:
Description: Lambda API Deployment
RestApiId: !Ref ApiGatewayRestApi
Outputs:
test:
Value: !Ref ApiGatewayRestApi
从浏览器控制台测试端点的脚本 -
let url = "enterUrlHere";
fetch(url, {
method : "POST"
})
.then(function(response) {
console.log('success =>\n', response);
})
.catch(function(error) {
console.log('error =>\n', error);
});
错误 -
No 'Access-Control-Allow-Origin' header is present on the requested resource.
【问题讨论】:
-
在试用 AWS CloudFormation + API Gateway 时的一个常见错误是您忘记将 API 重新部署到所需的阶段。请确保您已将所有内容部署到舞台
-
@MaiKaY 我在移动部署资源后再次尝试 - 最后
ApiGatewayDeployment,仍然是同样的错误,更新了问题中的模板。 -
只要您不使用 AWS SAM(无服务器应用程序模型),
AWS::ApiGateway::Deployment资源只会创建一次。这意味着一旦您更改 API 中的某些内容,您就需要再次手动部署 API(!)。 -
那么尽管有 CF 模板,但我需要部署一次网关吗?您是否可以复制问题中的模板并更正顺序并作为答案发布?我尝试了各种组合,但没有一个对我有用。
标签: amazon-web-services cors amazon-cloudformation