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

查看:22
本文介绍了如何使用 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.

应用程序的一个部分是一个回调 url,Amazon SNS 通知被发布到.

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.

这是执行此操作的中间件代码:

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

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

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

util = require('./util');

在您的 app.js 中并通过包含调用:

in your app.js and invoked by including:

app.use(util.overrideContentType());

之前

app.use(express.bodyParser());

app.js 文件中.这允许 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天全站免登陆