Flask and React routing Flask and React routing flask flask

Flask and React routing


We used catch-all URLs for this.

from flask import Flaskapp = Flask(__name__)@app.route('/', defaults={'path': ''})@app.route('/<path:path>')def catch_all(path):    return 'You want path: %s' % pathif __name__ == '__main__':    app.run()

You can also go an extra mile and reuse the Flask routing system to match path to the same routes as client so you can embed the data client will need as JSON inside the HTML response.


Maybe as extension to the answers before. This solved the problem for me:

from flask import send_from_directory@app.route('/', defaults={'path': ''})@app.route('/<path:path>')def serve(path):     path_dir = os.path.abspath("../build") #path react build     if path != "" and os.path.exists(os.path.join(path_dir, path)):         return send_from_directory(os.path.join(path_dir), path)     else:         return send_from_directory(os.path.join(path_dir),'index.html')


For some reason, the catch-all URLs did not work for me. I found that using the flask 404 handler results in the exact same thing. It sees the url and passes it down to react where your router will handle it.

@app.errorhandler(404)   def not_found(e):     return app.send_static_file('index.html')