【问题标题】:Nodejs - AWS SNS publish is called, but message is not being sentNodejs - 调用 AWS SNS 发布,但未发送消息
【发布时间】:2021-05-06 14:43:20
【问题描述】:

我正在尝试向单个用户发布 SNS 消息。 当我手动按下 AWS 控制台中的“发布端点”按钮时,该消息正在工作,但我正在尝试使用 SNS nodejs SDK 以编程方式发送它。

我已确保创建一个 IAM 角色,授予对 SNS 的完全访问权限。

我已经确定配置好了:

const AWS = require("aws-sdk");
AWS.config.update({
    region: process.env.AWS_REGION,
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});

我首先使用 sns.createPlatformEndpoint(endPointParams) 创建了一个平台端点,它工作正常,所以我的 IAM 角色不是问题。

使用该调用的结果,我使用data 创建publishParams 在创建端点后立即进行调用:

let payload = {
        user : "Hihih test",
        shopping_list : "shopping_item"
    };

    let endPointParams = {
        PlatformApplicationArn: process.env.REACT_APP_SNS_ARN,
        Token: req.body.device_token
    }

const createEndPoint = sns.createPlatformEndpoint(endPointParams).promise();
    createEndPoint.then(data => {

        console.log(data.EndpointArn);
        console.log(JSON.stringify(payload));
        
        let publishParams = {
            Message: JSON.stringify(payload),
            MessageStructure: 'json',
            TargetArn: data.EndpointArn
        };

        sns.publish(publishParams, (err, result1) =>{
            console.log("Success");
        });

        return;
    }).then(result => {
        
        res.status(200).send("Success sending invite to user.");

    }).catch(err => {
        console.log(err);
        res.status(500).send("Something went wrong sending the invite.");
    });
});

sns.publish() 内部的 console.log("Success"); 被触发,但在客户端,应用程序没有收到消息。我也多次尝试在控制台中手动调用“发布消息”,效果很好。

那么我的问题可能是什么?我认为我的代码有问题。

【问题讨论】:

  • 您是否查看了 SNS 的 CloudWatch 指标以确定“NumberOfNotificationsFailed”?
  • 请记住,您在打印“Success”时并未实际检查是否设置了err,因此这可能是首先要检查的内容。
  • @404 老实说,我认为.catch 会发现错误(我的错误哈​​哈)。添加另一个err 签入.publish 后,它给了我一个错误,我需要使用“GCM”或“默认”键来构造我的有效负载。这解决了我的问题。谢谢哈哈
  • @ChrisWilliams 我可能为 SNS 配置了错误的 CloudWatch 指标,因为它只是在 NotificationsFailed 中为 0 的已发布消息保持为 1。我已经检查了所有可用的框 (5) 并将持续时间设置为 3 小时,但我不知道为什么即使我手动发布消息,任何字段都没有增加。 i.imgur.com/ywjEDEa.png

标签: node.js amazon-web-services amazon-sns


【解决方案1】:

将 SNS 与 GCM 结合使用时,您需要使用键 GCMdefault 构建 JSON 有效负载,否则会引发错误。

var payload = {
    default: 'Hello World',
    GCM: {
        notification: {
            title: 'Hello World',
            body: 'Notification Body'
            // other configs can be put here
        }
    }
  };

【讨论】:

    猜你喜欢
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多