4

I want to serve a react app with flask, but the "static_folder" does not seem to work. This is my very minimal code:

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)

In the browser I can reach 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 both return a 404 not found error.

From what I understand, if I specify a static_folder I should reach all files from that folder from the root url. What am I missing / missunderstanding?

Jodo
  • 4,515
  • 6
  • 38
  • 50

2 Answers2

4

No, that's not what the documentation says:

  • 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.

So, your files would be served at localhost:5000/react_app/build. Since that's probably not what you want, you should pass static_url_path as well, with a value of something like "static", so that you can find the files at localhost:5000/static.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

Just want to add an important point. Do not forget to add static_url_path='' because it removes any preceding path from the URL (i.e. the default /static).I am not seeing this in you code snippet.

For example,

 app = Flask (__name__,
            static_url_path='', 
            static_folder='web/static',
            template_folder='web/templates')
  • static_url_path='' removes any preceding path from the URL (i.e. the default /static).
  • static_folder='web/static' to serve any files found in the folder web/static as static files.
  • template_folder='web/templates' similarly, this changes the templates folder.