如何通过Fetch向Node.js服务器发送XML数据并解决接收空值及响应问题
问题排查与解决:Fetch发送XML到Node.js服务器无数据且无响应
问题描述
通过Fetch方法将XML数据发送至Node.js服务器时,API调用能发起,但存在两个问题:
- Node.js接口中
req.body为空,无法获取到发送的XML数据 - Fetch方法无法接收服务器返回的响应信息
原Fetch代码
fetch('http://localhost:1000/api/Base64', { mode: 'no-cors', method: 'POST', body: JSON.stringify(result.value), headers: new Headers({'Content-Type': 'application/json'}), }) .then(response => { return response console.log(response); } ).then(data => { console.log(data); }).catch(err=>{console.log('errr handled in',err)})
原Node.js接口代码
export const Base64 = async (req, res) => { console.log(req.body); res.status(200).send({ msg: 'done' }); };
问题原因分析
mode: 'no-cors'的限制:该模式下浏览器会强制限制请求行为,不仅会屏蔽响应内容的读取权限,还可能自动修改请求头,导致服务器无法正确解析请求体。- 请求内容与Header不匹配:将XML字符串用
JSON.stringify()转换后,设置Content-Type: application/json,但实际发送的是JSON包裹的XML文本,服务器若未对应解析则无法识别。 - Node.js未配置请求体解析中间件:默认情况下Express等框架不会自动解析非表单、非JSON的请求体,导致
req.body为空。
解决方案
1. 移除no-cors模式并配置服务器CORS
no-cors是问题核心,直接移除该配置,同时在Node.js服务器端配置CORS以支持跨域请求:
# 安装CORS依赖 npm install cors
2. 修正Fetch请求,正确发送XML数据
直接发送原始XML字符串,设置对应Content-Type:
fetch('http://localhost:1000/api/Base64', { method: 'POST', body: result.value, // 直接传递XML原始字符串 headers: new Headers({ 'Content-Type': 'text/xml', // 匹配XML内容的Header }), }) .then(response => { if (!response.ok) throw new Error('请求失败'); return response.json(); // 解析服务器返回的JSON响应 }) .then(data => { console.log('服务器响应:', data); }) .catch(err => { console.log('错误:', err); })
3. 配置Node.js服务器的XML解析中间件
安装并配置body-parser来解析XML格式的请求体:
# 安装body-parser依赖 npm install body-parser
在服务器入口文件添加配置:
const express = require('express'); const cors = require('cors'); const bodyParser = require('body-parser'); const { Base64 } = require('./你的接口文件路径'); const app = express(); // 启用CORS app.use(cors()); // 配置XML解析中间件 app.use(bodyParser.text({ type: 'text/xml' })); // 注册接口 app.post('/api/Base64', Base64); app.listen(1000, () => { console.log('服务器运行在端口1000'); });
4. 修正接口函数验证数据
此时req.body将能获取到XML字符串:
export const Base64 = async (req, res) => { console.log('接收到的XML数据:', req.body); res.status(200).send({ msg: 'done' }); };
内容的提问来源于stack exchange,提问作者sachin wani
相关产品推荐
相关产品推荐

