无服务器 - Lambda 层“找不到模块‘请求’”

Mik*_*zzo 8 aws-lambda serverless-framework aws-serverless

当我使用以下方法部署我的无服务器 API 时:

serverless deploy
Run Code Online (Sandbox Code Playgroud)

lambda 层已创建,但是当我运行该函数时,出现此错误:

"Cannot find module 'request'"
Run Code Online (Sandbox Code Playgroud)

但是,如果我通过控制台手动上传 .zip 文件(部署时上传的完全相同的文件),它工作正常。

任何人都知道为什么会发生这种情况?

environment:
SLS_DEBUG: "*"

provider:
name: aws
runtime: nodejs8.10
stage: ${opt:api-type, 'uat'}-${opt:api, 'payment'}
region: ca-central-1
timeout: 30
memorySize: 128
role: ${file(config/prod.env.json):ROLE}
vpc:
    securityGroupIds:
    - ${file(config/prod.env.json):SECURITY_GROUP}
    subnetIds:
    - ${file(config/prod.env.json):SUBNET}
apiGateway:
    apiKeySourceType: HEADER
apiKeys:
    - ${file(config/${opt:api-type, 'uat'}.env.json):${opt:api, "payment"}-APIKEY}

functions:
- '${file(src/handlers/${opt:api, "payment"}.serverless.yml)}'

package:
# individually: true
exclude:
    - node_modules/**
    - nodejs/**

plugins:
- serverless-offline
- serverless-plugin-warmup
- serverless-content-encoding

custom:
contentEncoding:
    minimumCompressionSize: 0 # Minimum body size required for compression in bytes

layers:
nodejs:
    package:
    artifact: nodejs.zip
    compatibleRuntimes:
    - nodejs8.10
    allowedAccounts:
    - "*"
Run Code Online (Sandbox Code Playgroud)

这就是我的无服务器 yaml 脚本的样子。

cod*_*ire 5

layers在使用您用来定义 lambda 层的显式键时,我遇到了与您类似的错误。

我的错误(为了网络搜索)是这样的:

Runtime.ImportModuleError: Error: Cannot find module <package name>

我觉得这是一个临时解决方案,因为我想像您一样明确定义我的图层,但它不起作用,所以它看起来像是一个错误。

我针对此问题在无服务器中创建了错误报告。如果其他人也遇到同样的问题,他们可以在那里跟踪它。

解决方案

我根据AWS 的这些文档在无服务器论坛中关注了这篇文章

node_modules我把我的文件夹压缩到了下面nodejs,所以解压后看起来像这样nodejs/node_modules/<various packages>

然后,我没有使用层的显式定义,而是使用了packageartifact键,如下所示:

layers:
  test:
    package:
      artifact: test.zip
Run Code Online (Sandbox Code Playgroud)

在函数层中是这样引用的:

functions:
  function1:
    handler: index.handler
    layers:
      - { Ref: TestLambdaLayer }
Run Code Online (Sandbox Code Playgroud)

这是此处记录TestLambdaLayer的约定<your name of layer>LambdaLayer