从本地 JSON 文件中 fetch() 数据

问题描述 投票:0回答:1

即使 URL 路径看起来正确,我也对本地 JSON 文件上的 fetch 方法感到困惑。

提前致谢

   async function fetchLacsfromJSON(){
    try {
        const reponse = await fetch('/app/lacs.json', {
            method: 'GET',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
            } })
            if (reponse.ok){
              const lacsData= await reponse.json();
              return lacsData;
          }
          else  {   
            console.error(`Erreur HTTP : ${reponse.status} - ${reponse.statusText}`);} 
    } catch (error) {
      console.error(`Une erreur s'est produite : ${error.message}`);
    }
  }

错误消息是:无法从 /app/lacs.json 解析 URL

enter image description here 我期待在控制台上收到这个:

[{ "id":"1",
    "nom":"Lac d’Annecy",
    "region":"Auvergne-Rhône-Alpes"
    },
    {"id":"2",
     "nom":"Lac de Sainte Croix",
     "region":"Provence-Alpes-Côte d'Azur"
    },
    {"id":"3",
     "nom":"Lac du Salagou",
     "region":"Occitanie"
    }
]
json parsing fetch urlfetch
1个回答
0
投票

感谢您的帮助!我删掉了 : { “类型”:“模块” 在我的 package.json 中(因为我尝试了 node-fetch, import ...from)=> 没有用

以及我的异步函数(本地 JSON 文件)。

只需输入我的主控制器:

const lacsData =require('../lacs.json'); 

删除异步/获取组合后就足够了。

我使用 .map 方法在我的数据上检索了我的数据并且它有效

© www.soinside.com 2019 - 2024. All rights reserved.