SAM Node.js hello world 应用缺少 axios 模块

SAM Node.js hello world app has axios module missing

我是 Node.js 和 SAM 的新手。

我正在在线遵循 AWS 快速入门指南 here,只是我使用的是 Node.js。具体来说,我 运行 这些命令:

版本:

▶ sam --version 
SAM CLI, version 0.10.0
▶ node --version                                                               
v8.15.0

建造:

▶ sam init --runtime nodejs
▶ cd sam-app/
▶ sam build
▶ sam package \
  --template-file template.yaml \
  --output-template-file packaged.yaml \
  --s3-bucket $s3_bucket
▶ sam deploy \
  --template-file packaged.yaml \
  --stack-name sam-app \
  --capabilities CAPABILITY_IAM

这一切都很好地部署了堆栈和函数,但是当我测试它时它被破坏了,因为 axios 模块不存在:

{
  "errorMessage": "Cannot find module 'axios'",
  "errorType": "Error",
  "stackTrace": [
    "Function.Module._load (module.js:474:25)",
    "Module.require (module.js:596:17)",
    "require (internal/module.js:11:18)",
    "Object.<anonymous> (/var/task/app.js:2:15)",
    "Module._compile (module.js:652:30)",
    "Object.Module._extensions..js (module.js:663:10)",
    "Module.load (module.js:565:32)",
    "tryModuleLoad (module.js:505:12)",
    "Function.Module._load (module.js:497:3)"
  ]
}

Axios 模块似乎确实在构建目录中:

▶ ls -1 sam-app/.aws-sam/build/HelloWorldFunction/node_modules 
axios/
debug/
follow-redirects/
is-buffer/
ms/

但不在 Lambda 中:

我看过 其他 SO 答案,但没有帮助,因为我认为 SAM 应该打包它的所有依赖项。

有谁知道哪里出了问题吗?

sam build 将使用 node_modules 创建 sam-app 工件。但是当您使用 --template-file template.yaml 执行 sam package 时,上传到 s3 的工件将不包含应用程序依赖项,因为它根据定义的模板文件打包您的应用程序,而不是您从 sam build.

您应该删除 sam package 命令的 --template-file 参数。只需执行以下操作:

sam build
sam package --s3-bucket <your-bucket> --output-template-file packaged.yaml
sam deploy \
  --template-file packaged.yaml \
  --stack-name sam-app \
  --capabilities CAPABILITY_IAM

现在应该使用 package.json 中定义的依赖项创建 Lambda。

除此之外,这里的问题是为 Node.js 生成的文档包含一个拼写错误,指定了我使用的 sam package 命令,如 this 修订版中所示AWS SAM CLI 源代码。

我提出了一个拉取请求来修复它 here