您必须在 API Gateway 中有一个可用的方法。按照教程:使用 HTTP 非代理集成创建 REST API中的说明进行操作。
-
选择 API 资源,然后选择创建方法。
要创建方法,请执行以下操作:
对于方法类型,选择一种方法。
对于集成类型,选择模拟。
选择创建方法。
在方法请求选项卡上,对于方法请求设置,选择编辑。
-
选择 URL 查询字符串参数。选择添加查询字符串,然后为名称中输入
scope
。此查询参数确定调用方是否为内部。 -
选择保存。
-
在方法响应选项卡上,选择创建响应,然后执行以下操作:
-
对于 HTTP 状态,输入
500
。 选择保存。
-
-
在集成请求选项卡上,对于集成请求设置,选择编辑。
-
选择映射模板,然后执行以下操作:
选择添加映射模板。
对于内容类型,输入
application/json
。对于模板正文,输入以下内容:
{ #if( $input.params('scope') == "internal" ) "statusCode": 200 #else "statusCode": 500 #end }
选择保存。
-
在集成响应选项卡上,对于默认 - 响应,选择编辑。
-
选择映射模板,然后执行以下操作:
对于内容类型,输入
application/json
。对于模板正文,输入以下内容:
{ "statusCode": 200, "message": "Go ahead without me" }
选择保存。
-
选择创建响应。
要创建 500 响应,请执行以下操作:
-
对于 HTTP 状态正则表达式,输入
5\d{2}
。 对于方法响应状态,选择
500
。选择保存。
-
对于 5\d{2} - 响应,选择编辑。
选择映射模板,然后选择添加映射模板。
对于内容类型,输入
application/json
。对于模板正文,输入以下内容:
{ "statusCode": 500, "message": "The invoked method is not supported on the API resource." }
选择保存。
-
-
选择测试选项卡。您可能需要选择右箭头按钮,以显示该选项卡。要测试模拟集成,请执行以下操作:
-
在查询字符串下,输入
scope=internal
。选择 Test (测试)。测试结果显示:Request: /?scope=internal Status: 200 Latency: 26 ms Response Body { "statusCode": 200, "message": "Go ahead without me" } Response Headers {"Content-Type":"application/json"}
-
在
Query strings
下输入scope=public
或将其留空。选择 Test (测试)。测试结果显示:Request: / Status: 500 Latency: 16 ms Response Body { "statusCode": 500, "message": "The invoked method is not supported on the API resource." } Response Headers {"Content-Type":"application/json"}
-
您也可以首先将标头添加到方法响应,然后在集成响应中设置标头映射,从而在模拟集成响应中返回标头。实际上,这是 API Gateway 控制台通过返回 CORS 需要的标头来启用 CORS 支持的方法。