【问题标题】:How to enable CORS Headers for a Lambda Integration in AWS API Gateway, using the API Gateway API?如何使用 API Gateway API 在 AWS API Gateway 中为 Lambda 集成启用 CORS 标头?
【发布时间】:2019-07-09 06:42:28
【问题描述】:

我已经分叉了 Lambada framework 并开始对其进行修改以添加对 CORS 标头的支持。 Lambada 使用 API Gateway API [原文如此] 来配置 API Gateway。

作为概念验证,我在 API Gateway 控制台中手动验证了必要的更改,然后在自动化代码中寻找相应的步骤。我首先对org.lambadaframework.aws.ApiGateway 进行了这个简单的更改(为简洁起见,省略了导入):

我成功地重建了框架。不幸的是,当我尝试使用它部署新的 Lambda 时,我得到:

[ERROR] 未能执行目标 org.lambadaframework:lambada-maven-plugin:0.0.6-cors:deploy (默认) 在 MyApp 项目上:部署时出现异常:无效 指定的映射表达式:验证结果:警告:[],错误 :[指定的映射表达式无效:Access-Control-Allow-Origin] (服务:mazonApiGateway;状态代码:400;错误代码: 错误请求异常;请求 ID:16509b8e-30eb-11e9-bc6b-f5d1416f03b5) -> [帮助 1]

什么会导致这个失败?!我已经手动执行了相同的步骤(通过 ApiGateway 控制台),它在那里工作正常。最终,我怎样才能启用 CORS 标头?

类似问题,使用 CLI:api gateway CORS setup

【问题讨论】:

  • 应该是map.put("Access-Control-Allow-Origin","*") 为什么你使用 Boolean.FALSE ??
  • @RajarshiDas 好的,我尝试删除单引号并将 Boolean.FALSE 更改为 Boolean.TRUE。没有什么变化。错误消息完全相同。还有其他想法吗?如果有帮助,可以在此处docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/index.html?com/… 找到 API 文档。
  • map.put("Access-Control-Allow-Origin","*") 两者都用...这没有真假
  • @RajarshiDas 甚至无法编译。请仔细查看代码。
  • @RajarshiDas PutMethodResponseRequest::withResponseParameters 需要 Map

标签: cors aws-lambda aws-api-gateway


【解决方案1】:

这种情况下,设置集成响应参数时无需设置集成响应模板。

如果您喜欢使用集成响应来修改响应,请将内容类型指定为键,将响应模板指定为值。 2

假设您想修改内容类型为"application/json" 的响应,您的实现将是这样的:

/* replace the existing getResponseTemplate() method with this */
private Map<String, String> getResponseTemplate() {
    Map<String, String> params = new HashMap<String, String>();
    params.put(
        "application/json",
        "$input.json(\"$\")\n#set($context.responseOverride.header.Access-Control-Allow-Origin = \"*\")");
    return params;
}

【讨论】:

  • PutIntegrationResponseRequest::withResponseParameters 需要一个 Map,而 PutMethodResponseRequest::withResponseParameters 需要一个 Map
  • 所以您修改后的 getIntegrationResponseParameters() 会导致调用 PutIntegrationResponseRequest::withResponseParameters 时出现编译错误
  • 无论如何我都会尝试你的想法,假设你只是把方法名弄错了......
  • 我认为情况可能变得更糟:[错误] 无法在项目样板上执行目标 org.lambadaframework:lambada-maven-plugin:0.0.6-cors:deploy(默认):部署时出现异常:指定的映射表达式无效:验证结果:警告:[],错误:[指定的映射表达式无效:*,指定的映射表达式无效:integrati on.response.header.Access-Control-Allow-Origin](服务:AmazonApiGateway;状态代码:400;错误代码:BadRequestException;请求 ID:e378611f-34db-11e9-b5 9a-8b06fa5a2f86) -> [帮助 1]
  • 事件虽然失败了,但我觉得它更接近答案。我在这里推送了我的更改:github.com/atramos/lambadaframework/commit/…
猜你喜欢
  • 2021-03-08
  • 2020-08-17
  • 2021-09-15
  • 2017-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 2019-12-30
相关资源
最近更新 更多