Koa.js 中以下代码的等于是什么:
req.on('data', function(data) {
console.log(data);
}
You can stil access the node.js request but you should not do that!
var req = this.request.req;
Using co-body
you can parse JSON and form-encoded requests. If you want to handle another body type, you have to write your own middleware.
Here is a dummy middleware to handle XML requests:
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);
};
}
}
Usage:
var body = yield xml(this);