Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react router with flask back end

I am building a project with react as frontend and flask as backend. I want the application created by 'create-react-app' to use front end routing with 'react-router-dom' package. Relevant code in index.js:

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/about" component={About} />
    <Route component={Notfound} />
  </Switch>
</BrowserRouter>

Then I want to serve it via flask, so in flask I have following settings and routing rules:

app = Flask(__name__, static_folder="../build/static", template_folder="../build")

@app.route('/', defaults={'path': ''})
def serve(path):
    render_template("index.html")

Where index.html is built with npm run build. When I click on navbar and redirect to /about, app returns 404 not found.

Also there's another error in the browser console, which shows: Manifest: Line: 1, column: 1, Unexpected token.

Any help is appreciated.

like image 739
Kevin Fang Avatar asked Jul 16 '19 13:07

Kevin Fang


1 Answers

Its better to leave routing upto one party - either python (in your case flask) or react. The catch_all routing from flask app which is suggested in other comment, should only be used in development purpose, cause normally react apps are just static webapps which can be served with a generic http server (like nginx or apache in production). If you use the flask's catch_all alternative in production you will end up wasting resources as the same request could be handled directly from the http server instead of collecting the response from a wsgi server. Its like A, B and C are talking, A wants to call C, he could directly call C, but instead of doing so he asks B to call C, and C replies to B, then B relays the reply to A. Totally unnecessary resource usage. Besides it will get very confusing if you start/try to mix routing of both flask and react. Use one.

like image 156
Asif Mahmud Shimon Avatar answered Nov 12 '22 18:11

Asif Mahmud Shimon