Expressjs生体 [英] Expressjs raw body

查看:85
本文介绍了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天全站免登陆