简体   繁体   中英

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

I have a ReactJS frontend with multiple routes. eg: / , /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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM