如何通过假设一个默认的内容typesparsingExpress / NodeJs中的缺less内容types的HTTP请求?

如果快速bodyParser不启动,我怎么能访问POST请求中的数据?

 var server = express(); server.use(express.bodyParser()); server.post('/api/v1', function(req, resp) { var body = req.body; //if request header does not contain 'Content-Type: application/json' //express bodyParser does not parse the body body is undefined var out = { 'echo': body }; resp.contentType('application/json'); resp.send(200, JSON.stringify(out)); }); 

注意:在ExpressJs 3.x + req.body不是自动可用的,需要bodyParser来激活。

如果没有设置内容types标题,是否可以指定application/json的默认内容types并触发bodyParser

否则是否可以从这个快速POST函数内使用裸nodejs方式访问POST数据?

(例如req.on('data', function...

你有很多select,包括自己手动调用express(真正的)中间件函数(实际上,阅读源代码,它们只是函数,没有什么深奥的魔法可以混淆你)。 所以:

 function defaultContentTypeMiddleware (req, res, next) { req.headers['content-type'] = req.headers['content-type'] || 'application/json'; next(); } app.use(defaultContentTypeMiddleware); app.use(express.bodyParser()); 

我使用这个中间件之前,bodyParser踢,这可能会有所帮助。 它偷看请求stream的第一个字节,并猜测。 这个特定的应用程序只处理XML或JSON文本stream。

 app.use((req,res, next)=>{ if (!/^POST|PUT$/.test(req.method) || req.headers['content-type']){ return next(); } if ((!req.headers['content-length'] || req.headers['content-length'] === '0') && !req.headers['transfer-encoding']){ return next(); } req.on('readable', ()=>{ //pull one byte off the request stream var ck = req.read(1); var s = ck.toString('ascii'); //check it if (s === '{' || s==='['){req.headers['content-type'] = 'application/json';} if (s === '<'){req.headers['content-type'] = 'application/xml'; } //put it back at the start of the request stream for subsequent parse req.unshift(ck); next(); }); });