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 内容时 header 。
如何使用 body-parser 中间件提取上述所有请求正文内容?
最佳答案
我不认为你做错了什么,对我来说这看起来像是一个错误。 body-parser-xml
的代码很短,因此不难找到问题所在。
它创建 bodyParser.text
的内部实例,并将 type
设置为 ['*/xml', '+xml']
。到目前为止,一切都很好。然后,它通过“文本”解析器运行请求,以字符串形式读入 XML。如果请求的 content-type
是 text/plain
(或任何其他非 XML 类型),它将被忽略。那也好。问题出在下一步:
if(typeof req.body !== 'string') { return next(); }
它假设如果 req.body
是一个字符串,那么它一定来自其内部文本解析器。但这是一个错误的假设,因为 req.body
可能已经是来自早期中间件的字符串。
我建议您针对 body-parser-xml
提交错误。
避免此问题的最简单方法是交换 bodyParser.text
和 bodyParser.xml
的顺序。
关于node.js - Node.js 主体解析器中的错误 : Non-whitespace before first tag.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46866282/