调用时 AWS lambda 层错误 API "cannot find module"

AWS lambda layers error when call API "cannot find module"

我尝试使用 AWS Lambda 层,观看了有关它的教程,但我收到错误消息“找不到模块...”

service: aws-nodejs 

package:
  exclude:
    - .gitignore
    - package.json
    - .git/**

provider:
  name: aws
  profile: sandbox
  runtime: nodejs12.x

layers:
  testLayer:
    path: testLayer
    compatibleRuntimes:
      - nodejs12.x
    allowedAccounts:
      - '*'

functions:
  hello:
    handler: handler.hello
    layers:
      -  arn:aws:lambda:us-east-1:*:layer:testLayer:15
    events:
      - http:
          path: test
          method: get
          cors: true

当我部署它时,我的终端没有任何错误,在 AWS 上,我看到我的层,当我下载它时,我的 package.json 具有力矩依赖性,并且 node_modules 带时刻的文件夹

我的 handler.js 看起来像这样:

'use strict';
module.exports.hello = async (event, context) => {
    const moment = require('moment')
    const a = moment('2016-01-01')
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Hey' + a
    }),
  };
};

我的文件结构:

testLayer/
   node_modules/
      moment/
   package.json
serverless.yml
handler.js
package.json

你知道我做错了什么吗?

是的,您的节点模块可能在您的 lambda 层中,但 lambda 抛出“找不到模块...”的错误。

发生这种情况的原因可能是您创建的 zip 文件与 AWS documentation.

中提到的目录结构不符

根据官方文档:

Including Library Dependencies in a Layer You can move runtime dependencies out of your function code by placing them in a layer. Lambda runtimes include paths in the /opt directory to ensure that your function code has access to libraries that are included in layers.

To include libraries in a layer, place them in one of the folders supported by your runtime.

Node.js – nodejs/node_modules, nodejs/node8/node_modules (NODE_PATH)

Example AWS X-Ray SDK for Node.js

nodejs/node_modules/aws-xray-sdk

确保您的 zip 包含正确的目录结构,否则请尝试从 /opt/your_node_module_directory

导入您的模块