使用 Express 和 Node.js 从 HTTP 推送请求解析 XML 正文,使用 body-parser-xml



我需要使用Node.js express处理HTTP推送请求。

请求以XML格式发送正文,这就是为什么我选择body-parser- XML包进行解析。

我的问题是,正文没有被正确解析——我猜是因为包不识别传输正文的mime类型。

端点:

const express = require('express');
const bodyParser = require('body-parser');
require('body-parser-xml')(bodyParser);
const app = express();
const PORT = 8085;
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.xml({
limit:'25MB'
}));
app.post('/feed', function (req, res, body) {
console.log(req.headers);
console.log(req.body);
res.status(200).end();
});

输出:

{
host: 'localhost:8085',
accept: '*/*',
'x-meta-feed-type': '1',
'x-meta-feed-parameters': 'feed params',
'x-meta-default-filename': 'filename.xml',
'x-meta-mime-type': 'text/xml',
'content-length': '63'
encoding: 'UTF-8',
connection: 'Keep-Alive'
}
{
'<data id': '"1234"><name>Test</name><title>Test1234</title></data>'
}

我无法更改请求本身(它是外部的),只能更改Node.js端点。

知道如何正确处理内容吗?

谢谢你的帮助!

请求显然已被

app.use(express.urlencoded({ extended: true }));

中间件,这意味着它必须有Content-Type: application/x-www-form-urlencoded。删除两个app.use线,因为他们"global"Body-parsing决策(针对每个请求),而您只需要对一种类型的请求进行特殊处理。

如果您使用"非标准"&;(即错误的)类型,它将把内容解析为XML:

app.post('/feed',
bodyParser.xml({type: "application/x-www-form-urlencoded"}),
function (req, res) {
console.log(req.headers);
console.log(req.body);
res.status(200).end();
});

最新更新