如何向使用无服务器创建的 AWS Lambda 函数发送 post 请求

how to send post requests to AWS Lambda function created with serverless

TLDR

我不知道如何为使用无服务器

创建的 AWS Lambda API 格式化我的 post 请求

当前实施

我有一个使用 serverless 框架创建的 Lambda 函数。我有两个功能;一个打印出所有模块及其版本的函数,另一个函数对通过 post 请求发送的数据进行预测。它通过挂载 EFS 卷来处理依赖存储,这里是 serverless.yml

service: test3Predict

plugins:
  - serverless-pseudo-parameters

custom:
  efsAccessPoint: fsap-**********
  LocalMountPath: /mnt/efs
  subnetsId: subnet-**********
  securityGroup: sg-**********

provider:
  name: aws
  runtime: python3.6
  region: us-east-2
  timeout: 20

package:
  exclude:
    - node_modules/**
    - .vscode/**
    - .serverless/**
    - .pytest_cache/**
    - __pychache__/**

functions:
  ohPredict:
    handler: handler.lambda_handler_OH
    environment: # Service wide environment variables
      MNT_DIR: ${self:custom.LocalMountPath}
    vpc:
      securityGroupIds:
        - ${self:custom.securityGroup}
      subnetIds:
        - ${self:custom.subnetsId}
    iamManagedPolicies:
      - arn:aws:iam::aws:policy/AmazonElasticFileSystemClientReadWriteAccess
    events:
      - http:
          path: ohPredict
          method: get
    fileSystemConfig:
      localMountPath: '${self:custom.LocalMountPath}'
      arn: 'arn:aws:elasticfilesystem:${self:provider.region}:#{AWS::AccountId}:access-point/${self:custom.efsAccessPoint}'

  test:
    handler: handler.test
    environment: # Service wide environment variables
      MNT_DIR: ${self:custom.LocalMountPath}
    vpc:
      securityGroupIds:
        - ${self:custom.securityGroup}
      subnetIds:
        - ${self:custom.subnetsId}
    iamManagedPolicies:
      - arn:aws:iam::aws:policy/AmazonElasticFileSystemClientReadWriteAccess
    events:
      - http:
          path: test
          method: get
    fileSystemConfig:
      localMountPath: '${self:custom.LocalMountPath}'
      arn: 'arn:aws:elasticfilesystem:${self:provider.region}:#{AWS::AccountId}:access-point/${self:custom.efsAccessPoint}'

看来测试成功了;如果我 运行 sls deploy 并在浏览器中为我的 test 函数输入 URL,我会得到预期的输出。

问题

ohPredict 函数也无法正常工作。当我用 requests python 模块向它发送 post 请求时,

url = 'https://****.execute-api.****.amazonaws.com/dev/ohPredict'
myobj = {"data": data}
x = requests.post(url, json=myobj)
res = eval(x.text)
print(res)

我收到以下错误:

{'message': 'Missing Authentication Token'}

我 运行 使用简单的 lambda 函数和 post 请求进行测试,而不使用无服务器,这就是我需要的全部代码。我想我会尝试试验并提供一些值,结果我得到了这个:

url = 'https://****.execute-api.****.amazonaws.com/dev/ohPredict'
myobj = {"data": data}
x = requests.post(url, headers={'Authorization': 'FOO'}, json=myobj)
res = eval(x.text)
print(res)

导致:

{'message': "Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=FOO"}

我试过提供其他值,但输出没有任何变化。如何让我的 post 请求被我的函数接收?

正如yvesonline所说,问题出在方法上。只需将 method: get 替换为 method: post

即可解决此问题