用于将原始帖子数据保存在请求对象中的中间件不会“下一步".并导致超时 [英] middleware for saving raw post data in the request object won't "next" and cause timeout

查看:59
本文介绍了用于将原始帖子数据保存在请求对象中的中间件不会“下一步".并导致超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取Node/Express应用程序中特定端点的原始发布数据.我这样做:

I need to get the raw post data for a specific endpoint in a node/express app. I do:

app.use('/paypal/ipn',function(req, res, next) {
    var postData='';

    req.on('data', function(chunk) { 
        postData += chunk;
    });

    req.on('end', function() {
        req.rawBody = postData;
        console.log('ended buffering. result: ' + req.rawBody);
        next();
    });
});

发生的事情是,我在控制台中获得console.log输出,然后什么也没有发生.大约一分钟后,我看到服务器返回200-可能是超时.就像next()命令从不执行,或者执行并停滞.

What happens is that I get the console.log output in the console and then nothing happens. After a minute or so I see the server returns 200 - probably a timeout. It's like the next() command never executes, or executes and stales.

当我注释掉所有内容时,只需调用next():

When I comment out everything, and simply call next():

app.use('/paypal/ipn',function(req, res, next) {
    /*
    var postData='';

    req.on('data', function(chunk) { 
        postData += chunk;
    });

    req.on('end', function() {
        req.rawBody = postData;
        console.log('ended buffering. result: ' + req.rawBody);
        next();
    });
    */
    next();
});

一切正常,即调用了端点(当然,请求不包含rawBody).

Everything works, that is the endpoint is called (of course the request doesn't contain the rawBody).

所以看来我在缓冲rawBody的方式上做错了什么?是什么导致next()无法正常工作?

So it seems like I'm doing something wrong the way I buffer the rawBody? Something that causes next() not to work?

推荐答案

调用next()而不等待'end',以防止bodyParser和您的代码受到干扰.

Call next() without waiting for 'end', to prevent bodyParser and your code from interfering.

app.use(function(req, res, next) {
  req.rawBody = '';

  req.on('data', function(chunk) { 
    req.rawBody += chunk;
  });

  next();
});
app.use(express.bodyParser());

致敬 https://stackoverflow.com/a/21222540/1891397

这篇关于用于将原始帖子数据保存在请求对象中的中间件不会“下一步".并导致超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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