You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用fetch()读取本地JSON文件时遭遇URL解析失败问题求助

问题描述

使用fetch()读取本地JSON文件时触发URL解析错误,报错信息:Failed to parse URL from /app/lacs.json

相关代码

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}`);
    }
  }

预期输出

[
    { 
        "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"
    }
]
解决方法
  • 必须在本地服务器环境运行项目
    直接双击HTML文件打开时,浏览器使用file://协议,fetch()不支持该协议下的绝对路径(/app/...)。启动本地服务器的常用方式:

    • Python:项目根目录执行python -m http.server 8000(Python3)或python -m SimpleHTTPServer 8000(Python2)
    • Node.js:先全局安装http-server(npm install -g http-server),再在项目根目录执行http-server
      启动后通过http://localhost:8000访问页面,此时绝对路径会基于服务器根目录正常解析。
  • 校验文件实际路径
    确认lacs.json的位置:

    • 若服务器根目录为项目根文件夹,/app/lacs.json要求根目录下存在app文件夹,且lacs.json在其中
    • 若文件与当前HTML同级的app文件夹内,可改用相对路径./app/lacs.json,兼容性更好
  • 修正代码拼写错误
    代码中reponse为拼写错误,正确应为response,虽然不是当前URL错误的直接原因,但会影响后续逻辑,修正后代码如下:

    async function fetchLacsfromJSON(){
        try {
            const response = await fetch('/app/lacs.json', {
                method: 'GET',
                headers: {
                  'Accept': 'application/json',
                } })
                if (response.ok){
                  const lacsData= await response.json();
                  return lacsData;
              }
              else  {   
                console.error(`Erreur HTTP : ${response.status} - ${response.statusText}`);} 
        } catch (error) {
          console.error(`Une erreur s'est produite : ${error.message}`);
        }
      }
    
  • 移除冗余请求头
    GET请求无需设置Content-Type头(GET没有请求体),删除该头可避免潜在兼容性问题。

内容的提问来源于stack exchange,提问作者SparkH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:33:14