我尝试从头开始使用 AWS,运行构建基本的 Web 应用程序 https://aws.amazon.com/getting-started/hands-on/build-web-app-s3-lambda-api-gateway-dynamodb/教程。我想我可以一步一步地遵循它,并有一个简单的 Hello World 网页前端到一个小数据库。但我遇到了一个奇怪的错误:包括基本的、默认的aws-sdk
模块出现故障!
简洁版本:
这段代码:
// Include the AWS SDK module
const AWS = require('aws-sdk');
生成此错误:Error: Cannot find module 'aws-sdk'
很长的故事:
我正在逐步遵循该流程,使用 AWS 在线工具创建所有部分。当我创建 Lambda 函数时,第一个麻烦发生了。我不太担心创建函数工具显示 Node.js 版本 18.x,而不是教程的 Node.js 16.x,但我确实注意到它生成的 Lambda shell 被命名为index.mjs
代替index.js
。没问题,我将使用该文件。我用亚马逊的HelloWorld代码替换了内容。
// Define handler function, the entry point to our code for the Lambda service
// We receive the object that triggers the function as a parameter
exports.handler = async (event) => {
// Extract values from event and format as strings
let name = JSON.stringify(`Hello from Lambda, ${event.firstName} ${event.lastName}`);
// Create a JSON object with our response and store it in a constant
const response = {
statusCode: 200,
body: name
};
// Return the response constant
return response;
};
我使用他们的数据设置测试事件功能:
{
"firstName": "Ada",
"lastName": "Lovelace"
}
但运行代码产生了我的第一个错误:exports is not defined in ES module scope
对这个错误进行一些搜索让我陷入了远远超出基本教程范围的兔子洞,因此我将文件从 index.mjs 重命名为 index.js。重建后,效果很好:
{
"statusCode": 200,
"body": "\"Hello from Lambda, Ada Lovelace\""
}
我不会完成创建数据库的步骤,因为这不相关。一切都很好,直到我用访问数据库的代码替换了代码 - 它出现了上面的错误消息。为了简化问题,我删除了 Lambda 并使用上面的工作代码重新构建了它,并且require
陈述:
// Include the AWS SDK module
const AWS = require('aws-sdk');
// Define handler function, the entry point to our code for the Lambda service
// We receive the object that triggers the function as a parameter
exports.handler = async (event) => {
// Extract values from event and format as strings
let name = JSON.stringify(`Hello from Lambda, ${event.firstName} ${event.lastName}`);
// Create a JSON object with our response and store it in a constant
const response = {
statusCode: 200,
body: name
};
// Return the response constant
return response;
};
运行会生成以下输出:
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'aws-sdk'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/index.mjs",
"trace": [
"Runtime.ImportModuleError: Error: Cannot find module 'aws-sdk'",
"Require stack:",
"- /var/task/index.js",
"- /var/runtime/index.mjs",
" at _loadUserApp (file:///var/runtime/index.mjs:1000:17)",
" at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1035:21)",
" at async start (file:///var/runtime/index.mjs:1200:23)",
" at async file:///var/runtime/index.mjs:1206:1"
]
}
我在转储中看到的最奇怪的事情:它仍然引用index.mjs
即使我删除了该文件(或重命名它 - 我尝试了两种方法)。在在线 IDE 中,我只能访问仅显示 index.js 的文件树。我认为那是/var/task
所以我不知道在哪里/var/runtime
仍然包含对index.mjs
.
我很期待这个令人头疼的问题的解决方案。感觉它很简单,应该可以工作!