如何使用Lambda读取无服务器应用程序中的POST参数?

时间:2018-03-14 23:37:57

标签: amazon-web-services serverless-framework serverless

我将表单提交给无服务器部署的Lambda函数,这里是yml:

functions:
  hello:
    handler: handler.hello
    events:
      - http: POST hello

现在我的hello功能是:

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Se222rverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };

  callback(null, response);
};

我可以在输出中看到变量已传递,但它们存储在event.body属性中:

 "body":"email=test%40test.com&password=test12345"

现在我可以访问这个字符串,但是我无法从中读取单个变量,除非我做了一些正则表达式转换,我认为,在诸如serverless / aws这样的现代堆栈中不会出现这种情况。

我错过了什么?我如何阅读各个变量?

3 个答案:

答案 0 :(得分:2)

看起来您的无服务器端点正在使用Content-Type: application/x-www-form-urlencoded接收数据。您可以更新请求以使用JSON数据来访问post变量,就像使用其他JavaScript对象一样。

假设这不是一个选择;您仍然可以使用节点查询字符串模块来访问您的帖子正文数据来解析请求的正文,这是一个示例:

const querystring = require('querystring');

module.exports.hello = (event, context, callback) => {

  // Parse the post body
  const data = querystring.parse(event.body);

  // Access variables from body
  const email = data.email;

  ...

}

请记住,帖子正文中的某些参数是否使用无效JavaScript对象标识符的名称来使用方括号表示法,例如:

const rawMessage = data['raw-message'];

答案 1 :(得分:1)

您可以使用Node querystring模块来解析POST正文。

答案 2 :(得分:0)

各种编程模型的处理程序文档意味着API网关中的事件类型是低级流。这意味着您必须使用其他方法从POST中提取正文内容。

Input Format

{
    "resource": "Resource path",
    "path": "Path parameter",
    "httpMethod": "Incoming request's method name"
    "headers": {Incoming request headers}
    "queryStringParameters": {query string parameters }
    "pathParameters":  {path parameters}
    "stageVariables": {Applicable stage variables}
    "requestContext": {Request context, including authorizer-returned key-value pairs}
    "body": "A JSON string of the request payload."
    "isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
}

DOTNET Only the System.IO.Stream type is supported as an input parameter by default.

的Python event - 此参数通常是Python dict类型。它也可以是list,str,int,float或NoneType类型。