Axios获取XML响应后xml2json转换为空对象求助
问题描述
预期该API返回XML格式数据,使用console.log能正常查看并获取XML结构的response.data,但执行xml2json转换时返回空对象。
const headers = { 'Content-Type': 'application/x-www-form-urlencoded', }; const response = await axios.post(postURL, urlSearchParams, { timeout: constant.axiosTimeout, headers: headers }); // logger.custom.info('responseXML:: ', response); //Show list of things // logger.custom.info('responseXML_DATA:: ', response.data); //Empty console.log('responseXML:: ', response.data); //SUCCESS const options = { compact: true, trim: true, ignoreDeclaration: true, ignoreInstruction: true, ignoreAttributes: true, ignoreComment: true, ignoreCdata: true, ignoreDoctype: true, textFn: utils.xml2jsonRemoveJsonTextAttribute }; // JSON.parse(convert.xml2json(response.data, options)); console.log('xml2json:: ', convert.xml2json(response.data, options)); console.log('JSONParse:: ', JSON.parse(convert.xml2json(response.data, options)));


排查与解决方案
强制axios以文本形式获取响应
axios会根据响应的Content-Type自动解析数据,若API返回的类型标识不标准,可能导致XML解析异常。添加responseType: 'text'强制拿到原始XML字符串:const response = await axios.post(postURL, urlSearchParams, { timeout: constant.axiosTimeout, headers: headers, responseType: 'text' });校验XML格式合法性
把console.log输出的XML字符串复制到XML校验工具中,检查是否存在未闭合标签、特殊字符未转义等格式问题——xml2json对不合法的XML会直接返回空对象。简化xml2json转换选项
当前配置开启了大量忽略规则,若XML的核心数据在属性、CDATA中,会被直接过滤。先改用基础配置测试:const basicOptions = { compact: true }; console.log('basic xml2json:: ', convert.xml2json(response.data, basicOptions));能拿到数据后,再逐步添加需要的忽略项,避免误删有效内容。
排查自定义textFn函数
utils.xml2jsonRemoveJsonTextAttribute可能错误移除了所有文本节点,暂时注释该配置,看转换结果是否恢复正常:const options = { compact: true, trim: true, ignoreDeclaration: true, ignoreInstruction: true, ignoreAttributes: true, ignoreComment: true, ignoreCdata: true, ignoreDoctype: true // textFn: utils.xml2jsonRemoveJsonTextAttribute };
内容的提问来源于stack exchange,提问作者Jack Wong
相关产品推荐
相关产品推荐

