Expressjs 原始体 [英] Expressjs raw body

查看:19
本文介绍了Expressjs 原始体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问 expressjs 给我的请求对象的原始正文?

How can I access raw body of request object given to me by expressjs?

var express = require('./node_modules/express');
var app = express.createServer();
app.post('/', function(req, res)
{
    console.log(req.body); //says 'undefined'
});
app.listen(80);

推荐答案

默认 express 不会缓冲数据,除非您添加中间件来这样做.简单的解决方案是按照下面@Stewe 的答案中的示例进行操作,它只会自己连接所有数据.例如

Default express does not buffer data unless you add middleware to do so. The simple solution is to follow the example in @Stewe's answer below, which would just concatenate all of the data yourself. e.g.

var concat = require('concat-stream');
app.use(function(req, res, next){
  req.pipe(concat(function(data){
    req.body = data;
    next();
  }));
});

这样做的缺点是您现在已经将所有 POST 正文内容作为一个连续的块移动到 RAM 中,这可能不是必需的.另一种值得考虑但取决于您需要在帖子正文中处理多少数据的选项是将数据作为流处理.

The downside of this is that you have now moved all of the POST body content into RAM as a contiguous chunk, which may not be necessary. The other option, which is worth considering but depends on how much data you need to process in the post body, would be to process the data as a stream instead.

例如,对于 XML,您可以使用 XML 解析器,该解析器支持解析以块形式出现的 XML.一个这样的解析器是 XML Stream.你这样做:

For example, with XML you could use an XML parser that supports parsing XML as it comes in as chunks. One such parser would be XML Stream. You do something like this:

var XmlStream = require('xml-stream');

app.post('/', function(req, res) {
  req.setEncoding('utf8');
  var xml = new XmlStream(req);
  xml.on('updateElement: sometag', function(element) {
    // DO some processing on the tag
  });
  xml.on('end', function() {
    res.end();
  });
});

这篇关于Expressjs 原始体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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