I have a react project that is hosted in flask app.
This is the project folders:
/simzol/
└── backend/
├── app.py
└── build/
├── index.html
├── images/
├── static/
│ ├── css/
│ └── js/
└── other_files...
PS. the build folder is generated by react using the command "yarn build"
app = Flask(__name__, static_url_path="/static", static_folder="build/static", template_folder="build")
that's how I serve the main route and any other path that isn't an API path (which should be handled by the react app. If the page doesn't exist, react should return the appropriate 404 not found page that I wrote):
@app.route("/")
@app.route('/<path:path>')
def home(path=None):
try:
return render_template("index.html"), 200
except Exception as e:
return handle_exception(e)
When I run the app and go to the main route, I can't see my images load up.
What I tried:
static_url_path
to empty string ("") and the static_folder
to "build". That solves the problem but I encounter another problem when I surf any page that is not the root page (like /contactus) directly through the browser's url input field, I get 404 error from flask (not react)I wanted the images to load up in both flask app in production and in react app (using npm start
) for development. At the same time, I wanted unknown pages to be handled by react.
The most convenient solution I found is to put all the images under public/static/images
instead of public/images
and to change the src paths accordingly.
Then I can run yarn build
and get the result build folder to the flask app folder (backend
). That worked perfectly.