如何使用Express / Node.js访问Amazon SNS文章 [英] How do you access an Amazon SNS post body with Express / Node.js

查看:197
本文介绍了如何使用Express / Node.js访问Amazon SNS文章的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在在 Express 框架之上的Node.js中重建PHP应用程序。

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

应用程序的一部分是 Amazon SNS通知发布到的回调URL。

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

来自SNS的POST正文目前以PHP(以下方式)读取:

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

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

在Express中,我尝试了以下内容:

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:

{}

所以,重复一个问题:如何使用Express / Node.js访问Amazon SNS文章主体

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

推荐答案

另一种方法将修复 Content-Type 标题。

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

这里是中间件代码:

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();
  };
}

这假设有一个名为 util.js的文件 位于根项目目录中:

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

util = require('./util');

通过包括:

app.use(util.overrideContentType());

BEFORE

app.use(express.bodyParser());

这允许bodyParser()正确地解析正文...

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

较少干扰,然后您可以访问 req.body 正常。

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

这篇关于如何使用Express / Node.js访问Amazon SNS文章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆