调用 API 时 AWS lambda 层错误“找不到模块" [英] AWS lambda layers error when call API "cannot find module"

查看:45
本文介绍了调用 API 时 AWS lambda 层错误“找不到模块"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 AWS Lambda 层,观看了有关它的教程,但出现错误找不到模块..."

I try to use layers of AWS Lambda, watched a tutorial about it, but I get an error "cannot find module ..."

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 文件夹

When i deploy it, i don't have any errors in my terminal, and on AWS, i see my layer and when i download it, i have my package.json with moment dependency, and the node_modules folder with moment

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

my handler.js looks like this :

'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

你知道我做错了什么吗?

Do you have any idea of what i doing wrong ?

推荐答案

是的,可能您的节点模块位于 lambda 层中,但 lambda 却抛出找不到模块.."的错误.

Yes, it's possible that your node modules are there in your lambda layer and yet lambda is throwing error of "cannot find module..".

这可能是因为您创建的 zip 与 AWS 文档.

This may be happening because the zip that you have created is not as per directory structure mentioned in AWS documentation.

根据官方文档:

在层中包含库依赖项您可以移动运行时通过将它们放在一个层中,从你的函数代码中删除依赖项.Lambda 运行时在/opt 目录中包含路径以确保您的函数代码可以访问包含在层.

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)

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

适用于 Node.js 的 AWS X-Ray 开发工具包示例

Example AWS X-Ray SDK for Node.js

nodejs/node_modules/aws-xray-sdk

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

Make sure your zip contains correct directory structure else try importing your modules from /opt/your_node_module_directory

这篇关于调用 API 时 AWS lambda 层错误“找不到模块"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆