【问题标题】:How to subscribe a HTTP endpoint to SNS in node js?如何在节点 js 中将 HTTP 端点订阅到 SNS?
【发布时间】:2019-04-12 16:53:35
【问题描述】:

我正在尝试为我的端点订阅一个主题(我正在使用 EC2 实例),我尝试在浏览器中访问我的端点(GET 请求)以调用 sns.subscribe,但之后我没有收到 POST 请求。

我拨打sns.subscribe得到的回应是这样的。

{ ResponseMetadata: { RequestId: 'xxxx-xxxx-xxxx-xxx-xxxx' },
  SubscriptionArn: 'arn:aws:sns:topic_location:xxxx:topic_name:xxxx-xxxx-xxxx-xxx-xxxx' }

这是我的代码。

const express = require("express");
const AWS = require('aws-sdk');
const request = require('request')
const bodyParser = require('body-parser')
const app = express();
var SNS_TOPIC_ARN = "arn:aws:sns:topic_location:xxxx:topic_name";

// configure AWS
AWS.config.update({
    'accessKeyId': 'mykey',
    'secretAccessKey': 'mysecretkey',
    "region":"myregion"
});
const sns = new AWS.SNS();

app.get('/', (req, res) => {
    var params = {
        Protocol: 'http', /* required */   //http , https ,application
        TopicArn: SNS_TOPIC_ARN, /* required */   // topic you want to subscribe
        Endpoint: 'http://ec2-xx-xx-xx-xxx.myregion.compute.amazonaws.com/:80', // the endpoint that you want to receive notifications.
        ReturnSubscriptionArn: true //|| false
    };

    sns.subscribe(params, function (err, data) {
        if (err) {
            console.log(err);
        } else {
            console.log(data);

        }
    });
    res.end();
});

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.post('/', (req, res) => {
  let body = ''

  req.on('data', (chunk) => {
    body += chunk.toString()
  })

  req.on('end', () => {
    let payload = JSON.parse(body)

    if (payload.Type === 'SubscriptionConfirmation') {
      const promise = new Promise((resolve, reject) => {
        const url = payload.SubscribeURL

        request(url, (error, response) => {
          if (!error && response.statusCode == 200) {
            console.log('Yess! We have accepted the confirmation from AWS')
            return resolve()
          } else {
            return reject()
          }
        })
      })

      promise.then(() => {
        res.end("ok")
      })
    }
  })
})

app.listen(80, process.env.IP, function(request, response){
    console.log("## SERVER STARTED ##");
});

【问题讨论】:

  • 是否发布了任何数据?或者请求只是不包括 payload.Type === 'SubscriptionConfirmation' ?订阅后,您的亚马逊控制台是否显示您的订阅为 PendingConfirmation?
  • 据我所知,没有发布任何数据,在 aws 控制台上显示待确认

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


【解决方案1】:

调用sns.subscribe 时,我必须从端点中删除我的端口号!我的订阅现已得到确认:D 新端点如下所示。

Endpoint: 'http://ec2-xx-xx-xx-xxx.myregion.compute.amazonaws.com/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2016-08-25
    • 2022-11-20
    • 2017-04-20
    • 2014-02-23
    • 2015-01-14
    • 2016-07-02
    相关资源
    最近更新 更多