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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With