Nodejs - 调用 AWS SNS 发布,但未发送消息

时间:2021-02-02 12:03:05

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

我正在尝试向单个用户发布 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.");
    });
});

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

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

1 个答案:

答案 0 :(得分:0)

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

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