You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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,需要先安装对应依赖:

  1. 安装依赖:
npm install @aws-sdk/lib-dynamodb @aws-sdk/client-dynamodb
  1. 修正后的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 19:14:53