【发布时间】:2020-05-28 01:14:26
【问题描述】:
我有一个绑定到 API Gateway 的 Lambda 函数,我正在尝试从传递给 Lambda 函数的事件或上下文对象中获取路径和阶段。
AWS控制台生成的映射模板如下:
## See http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
## This template will pass through all parameters including path, querystring, header, stage variables, and context through to the integration endpoint via the body/payload
#set($allParams = $input.params())
{
"body-json" : $input.json('$'),
"params" : {
#foreach($type in $allParams.keySet())
#set($params = $allParams.get($type))
"$type" : {
#foreach($paramName in $params.keySet())
"$paramName" : "$util.escapeJavaScript($params.get($paramName))"
#if($foreach.hasNext),#end
#end
}
#if($foreach.hasNext),#end
#end
},
"stage-variables" : {
#foreach($key in $stageVariables.keySet())
"$key" : "$util.escapeJavaScript($stageVariables.get($key))"
#if($foreach.hasNext),#end
#end
},
"context" : {
"stage" : "$context.stage",
"source-ip" : "$context.identity.sourceIp",
"user" : "$context.identity.user",
"user-agent" : "$context.identity.userAgent",
"user-arn" : "$context.identity.userArn",
"request-id" : "$context.requestId",
"resource-id" : "$context.resourceId",
"resource-path" : "$context.resourcePath",
"account-id" : "$context.identity.accountId",
"api-id" : "$context.apiId",
"api-key" : "$context.identity.apiKey",
"authorizer-principal-id" : "$context.authorizer.principalId",
"caller" : "$context.identity.caller",
"cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider",
"cognito-authentication-type" : "$context.identity.cognitoAuthenticationType",
"cognito-identity-id" : "$context.identity.cognitoIdentityId",
"cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId",
"http-method" : "$context.httpMethod"
}
}
我正在尝试从上下文对象中获取舞台,如下所示:
exports.handler = function(event, context) {
console.log("Stage: " + context.stage);
...
}
但 logcat 显示为 Stage : undefined。
我还有其他查询参数,我可以像这样从事件对象的参数中提取这些参数
var id = event.params.querystring.id;
var publisher_id = event.params.querystring.publisher_id;
如何使用上述映射模板从上下文中提取路径和阶段值?
【问题讨论】:
-
您是否尝试过记录整个上下文以查看其中的内容?如果您更改了映射模板,请确保之后“部署”API Gateway 以使模板生效。
-
找到了一种从事件对象中获取它的方法。当然不是我想要的,但仍然需要看看为什么上下文没有给出它。
标签: node.js amazon-web-services aws-lambda aws-api-gateway