gpt4 book ai didi

amazon-web-services - CloudFormation API 网关 CORS 问题对 XMLHttpRequest 的访问被阻止

转载 作者:行者123 更新时间:2023-12-03 07:19:12 24 4
gpt4 key购买 nike

我正在尝试使用 CloudFormation 创建 API 网关,但遇到 CORS 问题。

前端错误:

POST https://<>.execute-api.us-east-1.amazonaws.com/prod/<> 500
new:1 Access to XMLHttpRequest at '<>' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • API 的创建没有任何问题,我什至根据工作 API 仔细检查了控制台上的每个页面,发现它们的 Method Request 没有任何差异。 , Integration Request , Integration ResponseMethod Response对于所有方法(包括 OPTIONS )。
  • 如果我删除模板创建的资源并在同一 API 网关中手动创建它们,那么我的代码将按预期工作。我已经使用 localhost、S3 存储桶和 PostMan 中的前端代码进行了测试,因此我可以验证我的前端代码、lambda 函数和数据库是否正常工作。
  • 我知道人们以前也遇到过这个问题,但我无法找到任何解决我的问题的答案。

  • 这是my template .

  • 请注意 "method.response.header.Access-Control-Allow-Origin": false实际上使用与工作 API 相同的设置创建 API。

  • 我还使用 correct answer for this question 中的代码.

  • 是的,我的 OPTIONS 请求具有“Access-Control-Allow-Origin” header 。

更新

下面是 dannymac 的回答。我得到了这些:

  • 我添加了console.log(event.requestContext);到我的 Lambda 函数(用 Node.js 编写)。
  • 测试函数时有 Lambda 的日志。
2019-06-27T20:07:03.118Z    462b93b2-9d4b-4ed3-bc04-f966fcd034cf    Debug CORS issue. Request ID:
2019-06-27T20:07:03.118Z 462b93b2-9d4b-4ed3-bc04-f966fcd034cf undefined
  • 看起来没有 event.requestContext .
  • 我选择了Enable CloudWatch Logs-INFOEnable Detailed CloudWatch MetricsCloudWatch log role ARN*:arn:aws:iam::<ID>:role/ApiGatewayCloudWatchLogsRole (这是 AWS 创建的角色)在 API Gateway 中设置。
  • 但是,没有CloudWatch记录API Gateway 。默认登录 CloudWatch - Log Groups :/aws/apigateway/welcome
Time (UTC +00:00)
2019-06-27
19:50:55
Cloudwatch logs enabled for API Gateway
  • 看起来像 CloudWatch日志没有从 API Gateway 获取测试.
  • 这是我通过测试 GET 得到的结果我的方法API Gateway :
Response Body
{
"message": "Internal server error"
}
Response Headers
{}
Logs
Execution log for request 10d90173-9919-11e9-82e1-dd33dda3b9df
Thu Jun 27 20:20:54 UTC 2019 : Starting execution for request: 10d90173-9919-11e9-82e1-dd33dda3b9df
Thu Jun 27 20:20:54 UTC 2019 : HTTP Method: GET, Resource Path: /notes
Thu Jun 27 20:20:54 UTC 2019 : Method request path: {}
Thu Jun 27 20:20:54 UTC 2019 : Method request query string: {userid=<ID>}
Thu Jun 27 20:20:54 UTC 2019 : Method request headers: {}
Thu Jun 27 20:20:54 UTC 2019 : Method request body before transformations:
Thu Jun 27 20:20:54 UTC 2019 : Endpoint request URI: https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-1:770402430649:function:test-api-gateway-2-LambdaFunction-1XDONAN3QIY9I/invocations
Thu Jun 27 20:20:54 UTC 2019 : Endpoint request headers: {x-amzn-lambda-integration-tag=... [TRUNCATED]
Thu Jun 27 20:20:54 UTC 2019 : Endpoint request body after transformations: {"resource":"/notes","path":"/notes","httpMethod":"GET","headers":null,"multiValueHeaders":null,"queryStringParameters":{"userid":"<USERID>"},"multiValueQueryStringParameters":{"userid":["<USERID>"]},"pathParameters":null,"stageVariables":null,"requestContext":{"path":"/notes","accountId":"<ID>"...,"identity":{"cognitoIdentityPoolId":null,"cognitoIdentityId":null,"apiKey":"test-invoke-api-key","principalOrgId":null,"cognitoAuthenticationType":null,"userArn":"<ARN>","apiKeyId":"test-invoke-api-key-id","userAgent":..."test [TRUNCATED]
Thu Jun 27 20:20:54 UTC 2019 : Sending request to https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-1:<ID>:function:test-api-gateway-2-LambdaFunction-<STRING>/invocations
Thu Jun 27 20:20:54 UTC 2019 : Received response. Status: 403, Integration latency: 6 ms
Thu Jun 27 20:20:54 UTC 2019 : Endpoint response headers: {Date=Thu, 27 Jun 2019 20:20:54 GMT, Content-Length=130, Connection=keep-alive, x-amzn-RequestId=<ID>}
Thu Jun 27 20:20:54 UTC 2019 : Endpoint response body before transformations: <AccessDeniedException>
<Message>Unable to determine service/operation name to be authorized</Message>
</AccessDeniedException>

Thu Jun 27 20:20:54 UTC 2019 : Lambda invocation failed with status: 403. Lambda request id: feb22917-0dea-4f91-a274-fb6b85a69121
Thu Jun 27 20:20:54 UTC 2019 : Execution failed due to configuration error:
Thu Jun 27 20:20:54 UTC 2019 : Method completed with status: 500
  • 我还在 Swagger 2 中导出了工作和不工作的 API 网关。唯一的区别是:
// working one:
"x-amazon-apigateway-any-method": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "noteid",
"in": "path",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"security": [
{
"mobile-notes-api-authorizer": []
}
]
}
// not working one:
"x-amazon-apigateway-any-method": {
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
}
}
},
"security": [
{
"test-api-gateway-2-authorizer": []
}
]
}
  • 他们都有:
"headers": {
"Access-Control-Allow-Origin": {
"type": "string"
},
"Access-Control-Allow-Methods": {
"type": "string"
},
"Access-Control-Allow-Headers": {
"type": "string"
}
}
  • 我尝试在 Body 中使用 Swagger 模板之前使用过我的API Gateway,但无法解决授权人无效的问题。

最佳答案

我已经解决这个问题了。主要有两点:

  1. Lambda 的 IntegrationHttpMethod 必须是 POST。我找到了答案here .
  2. 该模板没有允许 API Gateway 调用 Lambda 函数的 AWS::Lambda::Permission。通过该模板,当您使用 AWS::Lambda::Permission 时,它将将该 API 显示为 Lambda 函数的触发器。但是,如果您手动创建 API Gateway 并将其与 Lambda 函数链接,它不会将 API Gateway 显示为触发器,但它仍然有效。

因此,对于我上面发布的模板,我需要添加这些才能使其正常工作:

"LambdaPermission": {
"Type": "AWS::Lambda::Permission",
"Description": "Permission for API GateWay to invoke Lambda.",
"Properties": {
"Action": "lambda:invokeFunction",
"FunctionName": {
"Fn::GetAtt": [
"LambdaFunction",
"Arn"
]
},
"Principal": "apigateway.amazonaws.com",
"SourceArn": {
"Fn::Join": [
"",
[
"arn:aws:execute-api:",
{
"Ref": "AWS::Region"
},
":",
{
"Ref": "AWS::AccountId"
},
":",
{
"Ref": "ApiGateway"
},
"/*"
]
]
}
}
},

并将方法 ANY 编辑为如下所示

"methodNotesANY": {
"Type": "AWS::ApiGateway::Method",
"DependsOn": "LambdaPermission",
"Properties": {
"AuthorizationType": "COGNITO_USER_POOLS",
"AuthorizerId": {
"Ref": "GatewayAuthorizer"
},
"RestApiId": {
"Ref": "ApiGateway"
},
"ResourceId": {
"Ref": "resourceNotes"
},
"HttpMethod": "ANY",
"Integration": {
"Type": "AWS_PROXY",
"IntegrationHttpMethod": "POST",
"Uri": {
"Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations"
},
"IntegrationResponses": [{
"StatusCode": "200"
}]
},
"MethodResponses": [{
"ResponseModels": {
"application/json": "Empty"
},
"StatusCode": "200"
}]
}
},

关于amazon-web-services - CloudFormation API 网关 CORS 问题对 XMLHttpRequest 的访问被阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56688796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com