首页 > 解决方案 > Heroku 中的 Flask 网络服务器在提供 CSS 文件时返回 404

问题描述

网站适用于除 CSS 文件之外的所有内容。静态图像有效,静态 javascript 有效,favicon 有效,但 CSS 返回 404。我尝试了不同的浏览器并在 Web 浏览器上缓存重新加载。

应用日志:

2021-08-04T15:17:38.416574+00:00 heroku[router]: at=info method=GET 
path="/static/css/index.css" host=redacted fwd="82.196.112.61"
dyno=web.1 connect=1ms service=7ms status=404 bytes=2332 protocol=https

2021-08-04T15:17:38.424598+00:00 heroku[router]: at=info method=GET 
path="/static/js/bootstrap.bundle.js" host=redacted fwd="82.196.112.61"
dyno=web.1 connect=0ms service=27ms status=200 bytes=208248 protocol=https

这是我的项目结构。它在本地运行良好,但是一旦我将它推送到 Heroku,CSS 就无法提供服务。

项目结构:

项目结构

应用程序.py:

from app import app

if __name__ == "__main__":
    app.run(host='0.0.0.0',
            port=33507,
            use_reloader = True)

__init__.py:

from flask import Flask, send_from_directory
from whitenoise import WhiteNoise
app = Flask(__name__)

# Allows the app to identify the static folder
app.static_folder = 'static'
app.wsgi_app = WhiteNoise(
    app.wsgi_app,
    root='static/')

@app.route("/static/<path:path>")
def static_dir(path):
    return send_from_directory("static", path)

#Configuration of application, see configuration.py, choose one and uncomment.
configuration = 'app.configuration.ProductionConfig'
#configuration = 'app.configuration.DevelopmentConfig'
app.config.from_object(configuration)
print('Running server on ' + app.config['ENV'] + '.')

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
print('Running database at', app.config['SQLALCHEMY_DATABASE_URI'])

from app import views, models

db.create_all()

标签: flaskheroku

解决方案


解决了

问题的根源在于 Heroku 区分大小写,而 Github 则不区分大小写。即使您在本地更改文件夹的大小写,它也不会被提交并推送到 Github,然后传播到 Heroku。

TL;DR:检查您的文件夹在本地、Github 和 Heroku 中是否以字母大小写形式存在。

GitHub:

在此处输入图像描述

代码:

在此处输入图像描述

在此处输入图像描述


推荐阅读