Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access an Amazon SNS post body with Express / Node.js

I'm in the process of rebuilding a PHP app in Node.js on top of the Express framework.

One part of the application is a callback url that an Amazon SNS notification is posted to.

The POST body from SNS is currently read in the following way in PHP (which works):

$notification = json_decode(file_get_contents('php://input'));

In Express I have tried the following:

app.post('/notification/url', function(req, res) {
    console.log(req.body);
});

However, watching the console, this only logs the following when the post is made:

{}

So, to repeat the question: How do you access an Amazon SNS post body with Express / Node.js

like image 599
timstermatic Avatar asked Aug 28 '13 09:08

timstermatic


People also ask

How do you push to the SNS topic?

Sign in to the Amazon SNS console . In the left navigation pane, choose Topics. On the Topics page, select a topic, and then choose Publish message. The console opens the Publish message to topic page.

What protocols does Amazon SNS support?

The notification message sent by Amazon SNS for deliveries over HTTP, HTTPS, Email-JSON and SQS transport protocols will consist of a simple JSON object, which will include the following information: MessageId: A Universally Unique Identifier, unique for each notification published.


1 Answers

Another approach would be to fix the Content-Type header.

Here is middleware code to do this:

exports.overrideContentType = function(){
  return function(req, res, next) {
    if (req.headers['x-amz-sns-message-type']) {
        req.headers['content-type'] = 'application/json;charset=UTF-8';
    }
    next();
  };
}

This assumes there is a file called util.js located in the root project directory with:

util = require('./util');

in your app.js and invoked by including:

app.use(util.overrideContentType());

BEFORE

app.use(express.bodyParser());

in the app.js file. This allows bodyParser() to parse the body properly...

Less intrusive and you can then access req.body normally.

like image 79
Paul Avatar answered Oct 04 '22 14:10

Paul