本文介绍了快速获取rawBody的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试从帖子中检索某些内容,并且需要传入请求中的rawBody属性.我如何找回它?

Hello I am trying to retrieve something from the post, and need the rawBody property from the incoming request. How can I retrieve it??

我尝试使用express.bodyParser(),并且在我的后处理程序中,我正在寻找req.rawBody,并且它是未定义的.

I tried using express.bodyParser() and in my post handler, I was looking for req.rawBody, and it was undefined.

我什至用connect.bodyParser()尝试了它,但是我仍然没有运气.我对rawBody的定义不确定.

I even tried it with connect.bodyParser(), but I still have no luck with it. I am getting undefined for rawBody.

我在stackoverflow网站上读时说他们已经删除了rawBody功能,但是提到将其添加到我们自己的中间件文件中是一种快速修复.我是新手,所以我不知道如何实现这一目标.下面是我的代码段.

I was reading on the stackoverflow site saying that they had removed the rawBody functionality, but mentioned that it is a quick fix to add it to our own middleware file. I am a newbie, so I do not have a clue as to how to achieve this. Below is my code snippet.

/**
 * Module dependencies.
 */

var express = require('express')
  , connect = require('connect')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
//app.use(express.bodyParser());
app.use(connect.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);



/**custom stuff**/

app.post('/upload',function(req, res){
        console.log(req.header('Content-Type'));
        console.log(req.header('Host'));
        console.log(req.header('User-Agent'));

        console.log(req.rawBody);
        console.log(req.body);
        res.send("<h1> Hello the response is "+req.body.username);
});

/** end**/

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

对此有任何帮助,我们深表感谢.

Any help with this is much appreciated.

谢谢.

推荐答案

您可以使用自己的中间件来做到这一点:

You can use your own middle ware to do this:

app.use(function(req, res, next){
   var data = "";
   req.on('data', function(chunk){ data += chunk})
   req.on('end', function(){
      req.rawBody = data;
      next();
   })
})

// Your route registration:
app.get('/', function(){// whatever...})

app.post('/test', function(req, res){
    console.log(req.rawBody);
    res.send("your request raw body is:"+req.rawBody);
})

这篇关于快速获取rawBody的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 00:07