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

Flask项目访问styles.css与script.js出现404错误求助

Flask静态资源404问题解决方案

核心问题分析

  1. 静态文件存放位置错误:script.js被放在templates目录下,Flask仅默认对外暴露static目录下的静态资源,templates目录仅用于模板渲染,无法通过URL直接访问其中的文件。
  2. 资源引用路径错误:CSS文件使用了相对路径../static/styles.css,当访问根路径/时,相对路径解析逻辑会导致资源定位失败;同时script.js的引用路径指向templates目录,无法被正确加载。
  3. 可能的权限问题:Ubuntu系统下,若static目录或文件的权限设置不当,Flask进程可能无法读取静态资源。

分步解决方案

1. 调整目录结构

将script.js从templates目录移动到static目录下,正确的项目结构应为:

├── app.py
├── static
│   ├── styles.css
│   └── script.js
└── templates
    └── index.html

2. 修正资源引用路径

推荐使用Flask内置的url_for函数生成静态资源URL,它能自动适配Flask的路由规则,避免路径错误:
修改index.html中的资源引用部分:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Description Viewer</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
    <input type="file" id="fileInput" accept="image/*">
    <div id="imageContainer"></div>
    <div id="description"></div>

    <script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>

若不想使用模板语法,也可以直接使用绝对路径:

<link rel="stylesheet" href="/static/styles.css">
<script src="/static/script.js"></script>

3. 修复Ubuntu系统文件权限(若前两步无效)

确保static目录及文件具备可读权限,执行以下命令:

# 赋予目录和文件可读可执行权限
chmod -R 755 /path/to/your/project/static
# 设置正确的文件所有者(替换your_username为你的系统用户名)
chown -R your_username:your_username /path/to/your/project/static

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:33:34