Flask:无法访问静态文件夹中的文件 (404)

Flask: files in static folder can not be reached (404)

我想用 Flask 提供 React 应用程序,但 "static_folder" 似乎不起作用。这是我的最小代码:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__, static_folder="react_app/build")
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return app.send_static_file("index.html")

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)

在浏览器中,我可以到达 http://localhost:5000 and it returns me the correct index.html. But all the static files like css and js files return a 404 error. For example there is a file: react_app/build/bundle.css or react_app/build/js/some_name.js. But typing http://localhost:5000/bundle.css or http://localhost:5000/js/some_name.js 两个 return 404 未找到错误。

据我了解,如果我指定 static_folder,我应该从根目录 url 访问该文件夹中的所有文件。我错过了什么/误解了什么?

不,那不是 the documentation 所说的:

  • static_url_path – can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.
  • static_folder – the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.

因此,您的文件将在 localhost:5000/react_app/build 提供。由于这可能不是您想要的,因此您也应该传递 static_url_path,其值类似于 "static",以便您可以在 localhost:5000/static.[=13] 中找到文件=]

只想补充一点。不要忘记添加 static_url_path='' 因为它会从 URL 中删除任何前面的路径(即默认的 /static)。我没有看到这个你的代码片段。

例如,

 app = Flask (__name__,
            static_url_path='', 
            static_folder='web/static',
            template_folder='web/templates')
  • static_url_path='' 从 URL(即 默认/静态)。
  • static_folder='web/static' 提供找到的任何文件 在文件夹 web/static 中作为静态文件。
  • template_folder='web/templates' 同样,这会改变模板 文件夹。