Serve React Production App (local Server) Through Flask-Python
I'm producing an application with these two technologies: React-app & Flask-Python. Its intended to run a react client to represent data received from Flask-server. The flask server and react client are on the same machine and communicate trough sockets (SocketIO).
In Dev mode, in order to run the application, I have to run the react server with npm start (node) and the flask server with python.
In production mode, after the react server is built, I have to serve the build folder with the serve option available on Node. Otherwise the app will not work properly (I think its because I use react-router, and when I go to another place of my react app, the browser cannot find the URL's specified. When serving the build folder with serve option of Node, no problem shows up).
So, my question is: Can I serve the build folder of my react application with flask instead of serve option of node? I want to do this, in order to eliminate the Node.js dependency so if I want to run my application on another machine, I will not have to install node.
Yes it's possible to do it in flask with
static folder/files. You need to create a folder which is called
static in your project. Imagine this folder structure:
├── server/ └── static/ ├── css/ ├── dist/ ├── images/ └── js/ index.html
For your react app the only thing you need do is to build
npm run build.
In flask you should set this static folder in order to be used. You need in a simplified version this:
# server.py from flask import Flask, render_template app = Flask(__name__, static_folder="../static/dist", template_folder="../static") @app.route("/") def index(): return render_template("index.html") @app.route("/hello") def hello(): return "Hello World!” if __name__ == "__main__": app.run()
So the root path
/ will show react. The
/hello path will show the response from flask.
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module