Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask and React routing

I'm building the Flask app with React, I ended up having a problem with routing.

The backend is responsible to be an API, hence some routes look like:

@app.route('/api/v1/do-something/', methods=["GET"]) def do_something():     return something() 

and the main route which leads to the React:

@app.route('/') def index():     return render_template('index.html') 

I'm using react-router in the React app, everything works fine, react-router takes me to /something and I get the rendered view, but when I refresh the page on /something then Flask app takes care of this call and I get Not Found error.

What is the best solution? I was thinking about redirecting all calls which are not calling /api/v1/... to / it's not ideal as I will get back the home page of my app, not rendered React view.

like image 723
knowbody Avatar asked Jun 03 '15 12:06

knowbody


People also ask

Can react and flask work together?

Now, we provide the proxy in react package. json file because we need to access the flask URL in order to get the API from our react app. In general what proxy does is, when we request into the javascript web server which serves the react frontend will automatically be redirected to the proxy key.

How do you routing in flask?

Step to run the application: Run the application using the following command. Output: Open the browser and visit 127.0. 0.1:5000/post/13, you will see the following output. The add_url_rule() function – The URL mapping can also be done using the add_url_rule() function.

Can react do routing?

React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.


2 Answers

We used catch-all URLs for this.

from flask import Flask app = Flask(__name__)  @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path):     return 'You want path: %s' % path  if __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.

like image 117
Dan Abramov Avatar answered Sep 28 '22 00:09

Dan Abramov


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') 
like image 27
Henrik Avatar answered Sep 27 '22 23:09

Henrik