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

Viewed 7157

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?

2 Answers

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