简体   繁体   English

使用 Flask 为 React 应用程序提供静态文件失败

[英]Serving React app with Flask fails with static files

I am trying to do a very simple thing, serve a react app with Flask, but all the suggestions in other threads doesn't really work and it's becoming frustrating.我正在尝试做一件非常简单的事情,用 Flask 提供一个 React 应用程序,但其他线程中的所有建议都不起作用,而且越来越令人沮丧。

I have a directory structure that looks like this:我有一个看起来像这样的目录结构:


client
      build
           static
           index.html

So all JS/CSS files are in the static directory.所以所有的 JS/CSS 文件都在 static 目录中。 I followed the usual advice and come up with this:我遵循了通常的建议并提出了以下建议:

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)

and with that, it does serve index.html from the build directory when I open the root url.这样,当我打开根 url 时,它会从构建目录中提供 index.html。 However, the trouble comes when the index.html loads, because all the static files are references like this static/js/file.js , that translates into GET request - localhost/static/js/file.js , and could not be found.但是,当 index.html 加载时,麻烦就来了,因为所有的静态文件都是这样的引用static/js/file.js ,转换为 GET 请求 - localhost/static/js/file.js ,并且无法找到. I figured out that in order to hit static/js/file.js successfully, I would need to use this url localhost/build/static/js/file.js .我发现为了成功命中static/js/file.js ,我需要使用这个 url localhost/build/static/js/file.js

So, I in order to access static files, I would have to add the build prefix everywhere.所以,为了访问静态文件,我必须在任何地方添加build前缀。 Is there a better way to solve this ?有没有更好的方法来解决这个问题?

After so many attempts and trying different options, I gave up on solving this with Flask.经过这么多次尝试和尝试不同的选择,我放弃了用 Flask 解决这个问题。 I found that I could just build the react app like this我发现我可以像这样构建 react 应用程序

export PUBLIC_URL=/build导出 PUBLIC_URL=/build

npm run build npm 运行构建

to produce all references to have the path that flask expects (build/static/*)生成所有引用以具有flask期望的路径(build/static/*)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM