在我的 React 项目公共(public)文件夹中,我有一个名为 mySurvey.xml 的文件,我想在 src 目录中读取该文件,因此为了简单起见,我尝试在 app.js 中读取它
因此,在我的 app.js 中,我尝试使用 fetch API 读取它,但它返回的是 index.html 文本作为响应,而不是文件的内容。
// Fetch Function
fetch("./mySurvey.xml")
.then(response => response.text())
.then(data=>{
console.log('File Data = ',data)
let parser = new DOMParser();
let xml = parser.parseFromString(data, "application/xml");
console.log('XML = ',xml);
})
.catch(error =>{
console.log('My Error = ',error);
在网络选项卡中,我检查了 fetch API 正在创建此网址 http://localhost:3000/mySurvey.xml
这会加载 html 页面并且不会放弃 xml 数据
请指导我我的方法是否正确或者是否有更好的方法!!
注意:- 公共(public)文件夹中有很多 xml 文件,例如 mySurvey.xml,我将收到基于文件名的文件名,我必须从中读取数据。
最佳答案
fetch('abc.xml')
.then((res) => res.text())
.then(xmlString => new window.DOMParser().parseFromString(xmlString, "text/xml"))
.then(data => setItem(data))
.catch((err) => {
console.log(err);
});
Fetch默认无法解析xml。因此,我使用 DOMParser 将字符串解析为 XML 对象。一旦获得 xml 对象,您就可以将其存储在您的状态中并按照您的意愿操作它
关于javascript - 如何从React JS中的react项目中的公共(public)目录中的文件读取xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66470374/