【问题标题】:Serving React app with Flask fails with static files使用 Flask 为 React 应用程序提供静态文件失败
【发布时间】: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 前缀。有没有更好的方法来解决这个问题?

【问题讨论】:

标签: python reactjs flask


【解决方案1】:

经过这么多尝试和尝试不同的选择,我放弃了用 Flask 解决这个问题。我发现我可以像这样构建 react 应用程序

导出 PUBLIC_URL=/build

npm 运行构建

生成所有引用以具有烧瓶期望的路径(构建/静态/*)

【讨论】:

    猜你喜欢
    • 2016-11-07
    • 1970-01-01
    • 2016-12-23
    • 2023-04-07
    • 2019-09-19
    • 1970-01-01
    • 2012-07-14
    • 2020-05-10
    • 2015-10-19
    相关资源
    最近更新 更多