【发布时间】:2020-05-23 23:26:17
【问题描述】:
我正在尝试做一件非常简单的事情,使用 Flask 提供一个 React 应用程序,但是其他线程中的所有建议都不起作用,这变得令人沮丧。
我的目录结构如下所示:
client
build
static
index.html
所以所有的 JS/CSS 文件都在静态目录中。我遵循了通常的建议并想出了这个:
app = Flask(__name__, static_folder='../client/build')
@app.route("/")
def serve():
"""serves React App"""
return send_from_directory(app.static_folder, "index.html")
@app.route("/static/<path:path>")
def static_proxy(path):
"""static folder serve"""
file_name = path.split("/")[-1]
dir_name = os.path.join(app.static_folder, "/".join(path.split("/")[:-1]))
return send_from_directory(dir_name, file_name)
这样,当我打开根 url 时,它会从构建目录中提供 index.html。但是,当 index.html 加载时,问题就来了,因为所有的静态文件都是像 static/js/file.js 这样的引用,它转换为 GET 请求 - localhost/static/js/file.js,并且找不到。我发现为了成功点击static/js/file.js,我需要使用这个网址localhost/build/static/js/file.js。
所以,为了访问静态文件,我必须在各处添加 build 前缀。有没有更好的方法来解决这个问题?
【问题讨论】:
-
您是否尝试过一些内置的实用功能,例如
send_static_file或url_for('static'...? -
无法弄清楚如何解决这两个问题