Search code examples
expressamazon-sns

aws sns confirm subscription request processing issue


I am trying to implement the aws sns service for a bucket in s3 and i am following this document https://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html according to this there will be subscribe url in the request for the confirmation subscription which will be coming to the url that we provide, but i am receiving empty body in the request. I tried to log the body but gave me an empty object. and tried by using the bodyparser but same result.

here is my route that i am implementing.

 router.post("/s3FileCallback", function (req, res) {
      debugger;
      var bodyParser = require('body-parser');
      var app = express();
      app.use(bodyParser.urlencoded({ extended: false }));
      app.use(bodyParser.json())
      if (req.get("x-amz-sns-message-type") == "SubscriptionConfirmation") {
        console.log("arn" + req.get("x-amz-sns-topic-arn"));
        const subscribeUrl = req.body.SubscribeURL;
        console.log("subscribeUrl" + subscribeUrl);
})

is there any thing i am missing. can any one point me in right direction please.


Solution

  • I found what i was missing,

    router.post('/s3FileCallback', function(req, res) {
        debugger;
        if (req.get('x-amz-sns-message-type') == 'SubscriptionConfirmation') {
            console.log('arn' + req.get('x-amz-sns-topic-arn'));
            const subscribeUrl = req.body.SubscribeURL;
            console.log('subscribeUrl' + subscribeUrl);
        }
    });
    

    I am using body parser as a middleware, amazon is sending content-type as text\plain in the post request thanks for this forum i did not realize the type until i came across this https://forums.aws.amazon.com/message.jspa?messageID=261061#262098

    so tried a work around to change the header before using the bodyparser

    app.use(function(req, res, next) {
        if (req.get('x-amz-sns-message-type')) {
            req.headers['content-type'] = 'application/json';
        }
        next();
    });
    app.use(bodyParser.json({ limit: '50mb' }));
    app.use(bodyParser.urlencoded({ limit: '50mb', extended: false }));
    

    so now the req is parsed as json.