【发布时间】:2021-06-24 18:44:20
【问题描述】:
我正在尝试为用 Go 编写的 Lambda 函数启用 CORS,下面是我的配置和代码。
这是我的 SAM 配置...
AuthBindApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Cors:
AllowOrigin: "'*'"
AllowMethods: "'POST,OPTIONS'"
AllowHeaders: "'X-Amz-Date,X-Api-Key,X-Amz-Security-Token,X-Requested-With,X-Auth-Token,Referer,User-Agent,Origin,Content-Type,Authorization,Accept,Access-Control-Allow-Methods,Access-Control-Allow-Origin,Access-Control-Allow-Headers'"
Auth:
DefaultAuthorizer: CognitoAuthorizer
Authorizers:
CognitoAuthorizer:
UserPoolArn: !GetAtt CognitoUserPool.Arn
AuthBindFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: functions/auth/bind
Handler: bind
Runtime: go1.x
Tracing: Active
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref AuthInfoTable
- Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action: "cognito-identity:GetOpenIdTokenForDeveloperIdentity"
Resource: "*"
Events:
ApiEvent:
Type: Api
Properties:
Path: /auth/bind
Method: POST
RestApiId: !Ref AuthBindApi
Auth:
Authorizer: CognitoAuthorizer
Options:
Type: Api
Properties:
Path: /auth/bind
Method: OPTIONS
RestApiId: !Ref AuthBindApi
...这是我的 lambda:
func handler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
...
return events.APIGatewayProxyResponse{
Headers: map[string]string{
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST,OPTIONS",
"Access-Control-Allow-Headers": "X-Amz-Date,X-Api-Key,X-Amz-Security-Token,X-Requested-With,X-Auth-Token,Referer,User-Agent,Origin,Content-Type,Authorization,Accept,Access-Control-Allow-Methods,Access-Control-Allow-Origin,Access-Control-Allow-Headers",
},
StatusCode: http.StatusOK,
}, nil
}
我还尝试指定所有可能的 HTTP 方法...但我总是收到以下错误消息:
Access to XMLHttpRequest at 'https://lc5zxsnfg5.execute-api.eu-west-1.amazonaws.com/Prod/bind' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我已经苦苦挣扎了 2 天,任何提示将不胜感激。
【问题讨论】:
-
您是否重新部署了 API?
-
是的,我做到了。
-
我之前也遇到过类似的问题,看看这个question。
-
我不明白,API 网关将是这个 lambda 的主要入口点,在 API 网关中你需要启用 cors。 docs.aws.amazon.com/apigateway/latest/developerguide/…
标签: go aws-lambda cors aws-serverless