例如,如果我们想用

得到-用户?name =鲍勃

or

获取/用户/鲍勃

如何将这两个例子作为参数传递给Lambda函数?

我在文档中看到了一些关于设置“映射from”的内容,但我在API Gateway控制台中找不到该设置。

method.request.path。在方法请求页面中定义了一个名为parameter-name的路径参数。 method.request.querystring。parameter-name用于在方法请求页面中定义的名为parameter-name的查询字符串参数。

尽管我定义了一个查询字符串,但我没有看到这两个选项。


当前回答

得到-用户?name =鲍勃

{
    "name": "$input.params().querystring.get('name')"
}

获取/用户/鲍勃

{
    "name": "$input.params('name')"
}

其他回答

让它工作的步骤是:

在API网关控制台中…

Go to Resources -> Integration Request Click on the plus or edit icon next to the templates dropdown (odd I know since the template field is already open and the button here looks greyed out) Explicitly type application/json in the content-type field even though it shows a default (if you don't do this it will not save and will not give you an error message) put this in the input mapping { "name": "$input.params('name')" } click on the check box next to the templates dropdown (I'm assuming this is what finally saves it)

查询字符串可以直接在lambda中用javascript解析

GET /user?name =鲍勃

 var name = event.queryStringParameters.name;

但是,这并不能解决GET用户/bob的问题。

为了回答我自己的一个问题,我遇到了这个技巧。

在API Gateway映射模板中,使用下面的代码来给出HTTP客户端发送的完整查询字符串:

{
    "querystring": "$input.params().querystring"
}

这样做的好处是,您不必在查询字符串中限制自己使用一组预定义的映射键。现在您可以接受查询字符串中的任何键值对,如果这是您想要的处理方式的话。

注意:上面只列出了VTL模板可用的变量$input.params(x)。内部可能会发生变化,querystring可能不再可用。

为了获取查询参数,您可以像这样在queryStringParameters对象中获取它们

const name = event.queryStringParameters.name;

第二个是一个干净的URL。如果你的路径是/user/{name},你可以像这样从pathParameters对象中获取值

const name = event.pathParameters.name;

正如@Jonathan的回答,在集成请求中标记使用Lambda代理集成后,在您的源代码中,您应该按以下格式实现通过502坏网关错误。

NodeJS 8.10:

exports.handler = async (event, context, callback) => {
  // TODO: You could get path, parameter, headers, body value from this
  const { path, queryStringParameters, headers, body } = event;

  const response = {
    "statusCode": 200,
    "headers": {
      "Content-Type": "application/json"
    },
    "body": JSON.stringify({
      path, 
      query: queryStringParameters,
      headers,
      body: JSON.parse(body)
    }),
    "isBase64Encoded": false
  };

  return response;
};

在重新运行API之前,不要忘记在API网关部署您的资源。 Response JSON只返回正文中正确的集合。 你可以从事件中获取路径,参数,头,体值

const {path, queryStringParameters, headers, body} = event;