错误:第一个标记之前的非空白。 在node.js body-parser中

var bodyParser = require('body-parser'), require('body-parser-xml')(bodyParser); function test(req, res) { console.log(req.body); res.sendStatus(200); } module.exports = { middleware: [ bodyParser.json(), bodyParser.text(), bodyParser.xml({ xmlParseOptions: { normalize: true, normalizeTags: true, explicitArray: true } }) ], '/test': [{ get: test }], } 

在上面的代码中,我试图提取application/xml, text/xml, application/json, text, text.plain, application/x-www-form-urlencoded

但是我得到的错误Error: Non-whitespace before first tag. 当我传递原始内容与text/plain标题。

我如何使用body-parser中间件来提取所有上面的请求主体内容?

我不认为你做错了什么,它看起来像一个bug。 body-parser-xml的代码很短,所以不难发现问题。

它创build一个bodyParser.text的内部实例,其type设置为['*/xml', '+xml'] 。 到现在为止还挺好。 然后它通过“文本”parsing器运行请求,以stringforms读取XML。 如果请求的content-typetext/plain (或任何其他非XMLtypes),它将被忽略。 这也很好。 问题是下一步:

https://github.com/fiznool/body-parser-xml/blob/3cf7784d6fae61d1d877da54ca56f31b2642975c/index.js#L27

 if(typeof req.body !== 'string') { return next(); } 

它假定如果req.body是一个string,那么它一定是来自它的内部文本parsing器。 但是这是一个不正确的假设,因为req.body可能已经是早期中间件的一个string了。

我build议你提交一个针对body-parser-xml的错误。

避免这个问题最简单的方法是切换bodyParser.textbodyParser.xml的顺序。