Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在react JS中从react项目的公共目录中读取xml?_Javascript_Reactjs_Axios_Fetch - Fatal编程技术网

Javascript 如何在react JS中从react项目的公共目录中读取xml?

Javascript 如何在react JS中从react项目的公共目录中读取xml?,javascript,reactjs,axios,fetch,Javascript,Reactjs,Axios,Fetch,在react项目公用文件夹中,我有一个名为mySurvey.xml的文件,我想在src目录中读取该文件,因此为了简单起见,我尝试在app.js中读取它 因此,在我的app.js中,我尝试使用获取API来读取它,但它返回index.html文本作为响应,而不是文件的内容 // Fetch Function fetch("./mySurvey.xml") .then(response => response.text()) .then(data=

在react项目公用文件夹中,我有一个名为mySurvey.xml的文件,我想在src目录中读取该文件,因此为了简单起见,我尝试在app.js中读取它

因此,在我的app.js中,我尝试使用获取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);
})


在网络选项卡中,我选中了FetchAPI正在创建此url http://localhost:3000/mySurvey.xml

这会加载html页面,不会放弃xml数据

请告诉我我的方法是正确的还是有更好的方法

注意:-像mySurvey.xml这样的公用文件夹中有很多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对象,就可以将其存储在您的状态中,并按照您的意愿对其进行操作

基本上,我的问题是无法在fetch中访问mySurvey.xmlrequest@John真奇怪。它应该从公用文件夹中获取,没有任何问题。我刚刚在我的机器上试用了一个新项目,它在哪个文件中工作,你写了获取API代码,你能分享这个文件的屏幕截图吗code@John据我所知,他在src的App.js中写道,在网络选项卡中,我检查了FetchAPI是否正在创建这个url,这将加载html页面,并且不会放弃xml数据