api 网关 CORS 设置

api gateway CORS setup

我正在尝试在部署脚本中使用 aws-cli 从命令行设置 aws CORS。 我使用以下 perl to shell 命令创建了 POST 资源。 我正在尝试将集成响应设置为“*”,就像启用核心一样。

aws apigateway put-method-response \ --region "$region" \ --rest-api-id "$api_id" \ --resource-id "$resource_id" \ --http-method "POST" \ --status-code 200 \ --response-models '{"application/json":"Empty"}' \ --response-parameters '{"method.response.header.Access-Control-Allow-Origin":true}'

当我运行以下命令设置积分值。

aws apigateway put-integration-response \ --region "$region" \ --rest-api-id "$api_id" \ --resource-id "$resource_id" \ --http-method "$method" \ --status-code 200 \ --response-template '{"application/json":"Empty"}' \ --response-parameters \ '{"method.response.header.Access-Control-Allow-Origin": "'*'"}'

我收到以下错误。

调用 PutIntegrationResponse 操作时发生客户端错误 (BadRequestException):指定的映射表达式无效:验证结果:警告:[],错误:[指定的映射表达式无效:*]

任何人都可以告诉我这个错误到底指的是什么,或者更好的方法来处理 api 网关部署脚本。

API 网关管理控制台有一个不错的 'Enable CORS' 功能,您可能已经看到了。至于使用 CLI 进行复制,我建议使用控制台功能,然后观察配置,并在 CLI 请求中使用相同的参数。

您看到的错误一定是由于值“*”的单引号转义不正确造成的,因为只有字符 * 是无效的。同样只是为了指出另一个潜在的问题,--response-templates '{"application/json":"Empty"}' 的输入是有效的,但与方法中的 --response-models 的解释不同-响应对象。对于使用该集成响应的所有 API 调用,该值会将响应主体设置为 "Empty"。要进行直通,只需不要设置 --response-templates

的值

问题确实是转义字符的正确方法。

--response-parameters '{"method.response.header.Access-Control-Allow-Origin":"'"'*'"'"}'

显然,这更多是关于了解格式化 JSON 的正确方法。