Quasar 2.6.0中使用xml2js报错:this.removeAllListeners不是函数
解决Quasar 2.6.0中xml2js报错TypeError: this.removeAllListeners is not a function
问题背景
在Quasar 2.6.0应用中执行XML解析逻辑时,实例化xml2js.Parser时抛出以下错误:
Error fetching or parsing the XML: TypeError: this.removeAllListeners is not a function
相关代码如下:
导入代码
import axios from "axios"; import xml2js from "xml2js";
解析函数
async fetchAbstracts() { try { const url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=33888705,18340043,19033662,20978265,23204432,23275034,23892238&retmode=xml'; const response = await axios.get(url); const xmlData = response.data; const parser = new xml2js.Parser({ explicitArray: false, ignoreAttrs: true }); parser.parseString(xmlData, (err, result) => { if (err) { throw err; } // 假设XML结构已知且一致 // 导航到摘要文本,此路径可能需要调整 const articles = result.PubmedArticleSet.PubmedArticle || []; articles.forEach(article => { const abstractText = article.MedlineCitation.Article.Abstract.AbstractText; // 若有多段或多部分,AbstractText可能是数组 if (Array.isArray(abstractText)) { abstractText.forEach((text, index) => { console.log(`Abstract Section ${index + 1}: ${text}`); }); } else { console.log(`Abstract: ${abstractText}`); } }); }); } catch (error) { console.error('Error fetching or parsing the XML:', error); } }
解决方案
1. 修正xml2js导入方式
Quasar 2基于Vite,默认使用ESM模块系统,xml2js的正确导入方式需要直接获取Parser类:
// 推荐:解构导入Parser import { Parser } from 'xml2js'; // 备选:从默认导出中提取Parser import xml2js from 'xml2js'; const Parser = xml2js.Parser;
2. 使用Promise风格解析方法
xml2js提供了Promise版本的parseStringPromise,更适配async/await语法,同时避免回调上下文导致的错误:
async fetchAbstracts() { try { const url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=33888705,18340043,19033662,20978265,23204432,23275034,23892238&retmode=xml'; const response = await axios.get(url); const xmlData = response.data; const parser = new Parser({ explicitArray: false, ignoreAttrs: true }); // 使用Promise版本解析XML const result = await parser.parseStringPromise(xmlData); const articles = result.PubmedArticleSet.PubmedArticle || []; articles.forEach(article => { const abstractText = article.MedlineCitation.Article.Abstract.AbstractText; if (Array.isArray(abstractText)) { abstractText.forEach((text, index) => { console.log(`Abstract Section ${index + 1}: ${text}`); }); } else { console.log(`Abstract: ${abstractText}`); } }); } catch (error) { console.error('Error fetching or parsing the XML:', error); } }
3. 确保xml2js版本兼容
安装最新稳定版xml2js,保证与ESM环境兼容:
npm install xml2js@latest # 或使用yarn yarn add xml2js@latest
4. SSR模式额外检查
如果应用使用Quasar SSR模式,无需额外配置,只要确保导入方式正确即可,xml2js在Node.js环境中可正常运行。
内容的提问来源于stack exchange,提问作者Bill
相关产品推荐
相关产品推荐

