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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With