使用bodyParser发送text/xml类型POST请求遇415错误及空体问题求助
解决text/xml类型POST请求发送与解析问题
后端配置确认
你的bodyParser配置本身逻辑正确,但要注意加载顺序——必须把text/xml解析中间件放在所有路由和其他解析中间件(如urlencoded)之前,避免请求被抢先处理。示例调整后的配置:
const bodyParser = require("body-parser"); // 优先加载text/xml解析规则 app.use(bodyParser.text({ type: "text/xml" })); // 若无需其他类型解析,可注释或删除以下配置 // app.use(bodyParser.urlencoded({ extended: false }));
可以在目标路由中添加日志,验证请求头和体是否正确接收:
app.post('/your-target-path', (req, res) => { console.log('实际请求Content-Type:', req.get('Content-Type')); console.log('解析后的请求体:', req.body); // 业务逻辑处理 res.sendStatus(200); });
前端请求发送规范
问题核心是前端未正确设置请求头和请求体格式,导致自动转为application/x-www-form-urlencoded。以下是不同场景的正确发送方式:
浏览器Fetch API
const xmlContent = '<root><user><id>123</id><name>test</name></user></root>'; fetch('/your-target-path', { method: 'POST', headers: { 'Content-Type': 'text/xml', // 强制指定类型 }, body: xmlContent // 直接传入XML字符串 }) .then(res => res.text()) .then(result => console.log(result));
Node.js Axios
const axios = require('axios'); const xmlContent = '<root><user><id>123</id><name>test</name></user></root>'; axios.post('/your-target-path', xmlContent, { headers: { 'Content-Type': 'text/xml' } }) .then(response => console.log(response.data));
关键注意事项
- 禁止用
FormData或普通表单提交XML,这类方式会自动修改请求头类型,导致后端无法识别。 - 确保XML字符串格式合法,避免语法错误导致解析失败。
若问题仍存在,可检查后端是否有CORS中间件反向代理(如Nginx)篡改请求头,或服务器防火墙拦截了特定类型的请求。
内容的提问来源于stack exchange,提问作者Lucas
相关产品推荐
相关产品推荐

