AWS Lambda报错:TypeError: PutCommand is not a constructor 求助
解决Lambda报错:TypeError: PutCommand is not a constructor
核心问题
你错误地从 @aws-sdk/client-dynamodb 包中导入了不存在的 PutCommand。这个包提供的是DynamoDB低级API,对应的写入命令是 PutItemCommand;而 PutCommand 属于高级API(DocumentClient),需要从 @aws-sdk/lib-dynamodb 包中获取。
两种解决方案
方案1:使用低级API(无需额外安装依赖)
直接将代码中的 PutCommand 替换为 @aws-sdk/client-dynamodb 内置的 PutItemCommand,无需修改现有依赖:
修正后的index.js代码:
const { DynamoDBClient, PutItemCommand } = require("@aws-sdk/client-dynamodb"); const client = new DynamoDBClient({ region: "us-east-2" }); exports.handler = async (event) => { const requestBody = JSON.parse(event.body); const email = requestBody.email; const params = { TableName: "WaitingList", Item: { email: { S: email } } }; // 替换为PutItemCommand const command = new PutItemCommand(params); try { await client.send(command); return { statusCode: 200, body: JSON.stringify("Successfully added to the waiting list"), }; } catch (error) { return { statusCode: 500, body: JSON.stringify(`An error occurred: ${error.message}`), }; } };
方案2:使用高级API(DocumentClient,简化数据格式)
如果想使用更简洁的参数格式(无需指定类型标识如{ S: email }),可以改用DocumentClient的PutCommand,需要先安装对应依赖:
- 安装依赖:
npm install @aws-sdk/lib-dynamodb @aws-sdk/client-dynamodb
- 修正后的
index.js代码:
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb"); const { PutCommand, DynamoDBDocumentClient } = require("@aws-sdk/lib-dynamodb"); const client = new DynamoDBClient({ region: "us-east-2" }); const docClient = DynamoDBDocumentClient.from(client); exports.handler = async (event) => { const requestBody = JSON.parse(event.body); const email = requestBody.email; // 高级API无需指定类型,直接传值 const params = { TableName: "WaitingList", Item: { email: email } }; const command = new PutCommand(params); try { await docClient.send(command); return { statusCode: 200, body: JSON.stringify("Successfully added to the waiting list"), }; } catch (error) { return { statusCode: 500, body: JSON.stringify(`An error occurred: ${error.message}`), }; } };
后续打包注意事项
- 执行打包前,确保依赖已正确安装在当前目录的
node_modules中 - 重新打包:
zip -r lambda-package.zip index.js node_modules/
- 上传新的压缩包到Lambda函数
额外排查点
- 确认Lambda的Runtime确实设置为Node.js 18.x
- 检查DynamoDB表
WaitingList已存在,且主键为email(字符串类型) - 确保Lambda角色拥有
dynamodb:PutItem权限(可在IAM角色中添加对应策略)
内容的提问来源于stack exchange,提问作者Meowzer
相关产品推荐
相关产品推荐

