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

Node.js AWS Lambda调用SNS Topic报错,请求协助修复

修复Node.js Lambda发送SNS消息的ES模块错误

我是AWS新手,尝试通过Node.js编写Lambda函数发送SMS至SNS Topic,但功能无法正常运行。以下是我的代码:

import { SNS } from "@aws-sdk/client-sns";
import * as AWS from "@aws-sdk/client-config-service";

AWS.config.update({region: 'us-east-1'});

// Lambda function handler
exports.handler = async (event, context) => {
  const sns = new AWS.SNS();

  // Get the current date and time in GMT+7
  const now = new Date();
  const gmt7Offset = now.getTimezoneOffset() + 7 * 60 * 60 * 1000;
  const gmt7Date = new Date(now.getTime() + gmt7Offset);

  // Generate random values for two dice rolls (between 1 and 6)
  const die1 = randomInt(1, 7);
  const die2 = randomInt(1, 7);

  // Format the date and time in GMT+7
  const dateTimeString = gmt7Date.toLocaleString();

  // Create the result string
  const result = `Giá trị khi tung 2 cục súc xắc ngẫu nhiên là ${die1} và ${die2}. Thời gian hiện tại là ${dateTimeString} (GMT+7).`;

  // Create the message parameters
  const messageParams = {
    Message: result,
    TopicArn: 'yarn:aws:sns:us-east-1:991676580242:Default_CloudWatch_Alarms_Topic:ff4f538e-5d7a-4394-871b-2c8716fa38aa' // Replace with your SNS topic ARN
  };

  // Publish the result to the SNS topic
  try {
    await sns.publish(messageParams).promise();
    console.log('Tin nhắn đã được gửi đến SNS thành công.');
  } catch (error) {
    console.error('Lỗi khi gửi tin nhắn đến SNS:', error);
    throw error;
  }

  const response = {
    statusCode: 200,
    body: JSON.stringify({ result }),
  };

  return response;
};

// Random integer function
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

我遇到的错误信息如下:

errorMessage: require is not defined in ES module scope, you can use import instead


问题原因与修复方案

  • 导入逻辑错误:混用ES模块import和旧版SDK全局配置模式,且导入了错误的包@aws-sdk/client-config-service,新版AWS SDK v3采用模块化设计,无需全局配置AWS.config。
  • SNS实例创建错误:错误使用AWS.SNS()创建实例,应直接使用导入的SNS客户端类。
  • Promise调用冗余:新版SDK的方法本身返回Promise,无需额外调用.promise()。
  • ARN格式错误:SNS Topic ARN开头应为arn:而非yarn:,且需移除多余的后缀字符。

修复后的完整代码

import { SNSClient, PublishCommand } from "@aws-sdk/client-sns";

// 初始化SNS客户端并指定区域
const snsClient = new SNSClient({ region: "us-east-1" });

exports.handler = async (event, context) => {
  // 正确计算GMT+7时间
  const now = new Date();
  const gmt7Date = new Date(now.getTime() + (7 * 60 * 60 * 1000) - (now.getTimezoneOffset() * 60 * 1000));
  
  const die1 = randomInt(1, 7);
  const die2 = randomInt(1, 7);
  
  const dateTimeString = gmt7Date.toLocaleString();
  const result = `Giá trị khi tung 2 cục súc xắc ngẫu nhiên là ${die1} và ${die2}. Thời gian hiện tại là ${dateTimeString} (GMT+7).`;
  
  const messageParams = {
    Message: result,
    TopicArn: 'arn:aws:sns:us-east-1:991676580242:Default_CloudWatch_Alarms_Topic'
  };

  try {
    // 使用新版SDK的命令模式发送消息
    await snsClient.send(new PublishCommand(messageParams));
    console.log('Tin nhắn đã được gửi đến SNS thành công.');
  } catch (error) {
    console.error('Lỗi khi gửi tin nhắn đến SNS:', error);
    throw error;
  }

  return {
    statusCode: 200,
    body: JSON.stringify({ result }),
  };
};

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

额外检查项

  1. Lambda权限配置:确保Lambda执行角色拥有sns:Publish权限,示例策略:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:us-east-1:991676580242:Default_CloudWatch_Alarms_Topic"
    }
  ]
}
  1. SNS Topic验证:确认Topic ARN正确,目标订阅者(如手机号)已完成订阅验证。

内容的提问来源于stack exchange,提问作者nhaemcotivi_1999

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:26:17