在Koa中等于req.on('data')

Koa.js中以下代码的等式是什么:

req.on('data', function(data) { console.log(data); } 

你可以stil访问node.js请求,但你不应该这样做!

 var req = this.request.req; 

使用co-body可以parsingJSON表单编码的请求。 如果你想处理另一种身体types,你必须编写自己的中间件。

这是处理XML请求的虚拟中间件:

 var raw = require('raw-body'); var parseXML = require('xml2js').parseString; function xml(req, opts) { req = req.req || req; // Parse Content-Type var type = (req.headers['content-type'] || '').split(';')[0]; if (type === 'application/xml') { return function(done) { raw(req, opts, function(err, str){ if (err) return done(err); try { // Parse XML request parseXML(str, function(err, result) { if (err) throw err; done(null, result); }); } catch (err) { err.status = 400; err.body = str; done(err); } }); }; } else { // Invalid request return function(done) { var err = new Error('Unsupported or missing content-type'); err.status = 415; done(err); }; } } 

用法:

 var body = yield xml(this);