eliasbenb
eliasbenb

Reputation: 179

How do I implement a ReactJS app into my Flask app?

I have a ReactJS frontend with multiple routes. e.g.: /, /example1, example1/example2/example3/example4.

I have used the react-build script to make production build of the ReactJS app. Now I'm trying to incorporate the ReactJS app with the Flask app.

This is what I have so far on my Flask routes:

app = Flask(__name__, static_folder="./build", static_url_path="")
CORS(app)
app.secret_key = secret_key


@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def serve(path):
    return app.send_static_file("index.html")

This works, but not for all routes. For example, /example1 and /example1/example2 work. But /example1/example2/example3 doesn't work. Any ideas? Thanks.

EDIT: It turns out that /example1/example2 does not work, meaning that the issue is to do with custom routes, which aren't predefined. All routes which I have specifically defined work, but the dynamically made ones don't.

Upvotes: 0

Views: 155

Answers (1)

Manish Sahani
Manish Sahani

Reputation: 186

https://blog.miguelgrinberg.com/post/how-to-deploy-a-react-router-flask-application - this might help you for now, the tutorial has modified the 404 exception handler (Not really an elegant solution but works).

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

Upvotes: 1

Related Questions