node.js - Node.js 主体解析器中的错误 : Non-whitespace before first tag.

标签 node.js express 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 内容时 header 。

如何使用 body-parser 中间件提取上述所有请求正文内容?

最佳答案

我不认为你做错了什么,对我来说这看起来像是一个错误。 body-parser-xml 的代码很短,因此不难找到问题所在。

它创建 bodyParser.text 的内部实例,并将 type 设置为 ['*/xml', '+xml']。到目前为止,一切都很好。然后,它通过“文本”解析器运行请求,以字符串形式读入 XML。如果请求的 content-typetext/plain(或任何其他非 XML 类型),它将被忽略。那也好。问题出在下一步:

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

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

它假设如果 req.body 是一个字符串,那么它一定来自其内部文本解析器。但这是一个错误的假设,因为 req.body 可能已经是来自早期中间件的字符串。

我建议您针对 body-parser-xml 提交错误。

避免此问题的最简单方法是交换 bodyParser.textbodyParser.xml 的顺序。

关于node.js - Node.js 主体解析器中的错误 : Non-whitespace before first tag.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46866282/

相关文章:

javascript - Node/Express API 路由中正确且可持续的错误处理方式

node.js - Express 在 ubuntu 上不起作用

javascript - 如何使用 Node.js 将图像路径保存在数据库中?

javascript - 如何让我的示例 bodyparser 工作?

node.js - Promise 或与 Node js 异步

node.js - 套接字发送到房间适用于除发送者之外的所有套接字

node.js - NodeJS 读取电子邮件 pop3

android - 移动应用不需要 CORS?

javascript - 当我输入并提交名称和 img url 时,它不会在其他页面上显示

node.js - 图片上传: Node Multer 'LIMIT_UNEXPECTED_FILE' error