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

Flask Web应用中使用Fetch获取JSON返回GET 404错误求助

解决Flask中静态JSON文件404的问题

1. 修正基础路径错误

你当前的fetch路径写的是../saved_json/data.json,但实际JSON文件所在文件夹是JSON_folder,这是直接导致404的核心原因之一。修正后的相对路径代码如下:

fetch('../JSON_folder/data.json')
.then(function(response){
    return response.json();
}).then(function(detections){
   console.log("test");
}).catch(function(error) {
   console.error('请求出错:', error);
});

建议添加catch捕获错误,方便后续排查其他潜在问题

2. 更稳妥的方案:使用Flask内置的静态资源路由

相对路径容易受页面路由层级影响,推荐用Flask的url_for生成绝对路径,彻底避免路径偏移问题:

方式一:在模板中注入JSON文件URL

在templates/index.html中,通过url_for生成静态文件的正确URL,直接在页面内编写请求逻辑:

<script>
const dataUrl = "{{ url_for('static', filename='JSON_folder/data.json') }}";
fetch(dataUrl)
.then(function(response){
    return response.json();
}).then(function(detections){
   console.log("test");
}).catch(function(error) {
   console.error('请求出错:', error);
});
</script>

方式二:全局变量传递URL给外部JS

如果要保留script.js的独立文件结构,可以在模板中把URL挂载到全局对象,再让外部JS调用:

<script>
window.dataJsonUrl = "{{ url_for('static', filename='JSON_folder/data.json') }}";
</script>
<script src="{{ url_for('static', filename='js/script.js') }}"></script>

然后在script.js中使用全局变量:

fetch(window.dataJsonUrl)
.then(function(response){
    return response.json();
}).then(function(detections){
   console.log("test");
}).catch(function(error) {
   console.error('请求出错:', error);
});

方式三:直接使用绝对路径

如果你的Flask应用根路径为/,可以直接写静态文件的绝对路径:

fetch('/static/JSON_folder/data.json')
.then(function(response){
    return response.json();
}).then(function(detections){
   console.log("test");
}).catch(function(error) {
   console.error('请求出错:', error);
});

3. 排查Flask配置问题(上述方法无效时)

确认你的Flask应用没有修改默认静态文件夹配置。默认情况下Flask会自动识别根目录下的static文件夹,若初始化时手动指定了static_folder,需确保JSON_folder在指定的文件夹内:

from flask import Flask

# 默认配置(无需手动编写,仅作参考)
app = Flask(__name__, static_folder='static')

内容的提问来源于stack exchange,提问作者Christian Paul Calso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:02:40