Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to serve on Flask and route to different endpoints/paths?

Tags:

angular

flask

I am trying to make an Angular application served with Flask to load the Angular app login page. Using just the https://domainname/ works fine, but I cannot route to https://domainname/login.

Steps to reproduce:

  • Clear browser cache
  • Open new tab and navigate to https://domainname/login
  • Returns 404

Initially I used another solution, but trying things along the way, I ended up with the approach suggested by Stack Overflow question Python (Flask) serving Angular project's index.html file

Flask Routes

@app.route('/<path:path>', methods=['GET'])
def static_proxy(path):
  return send_from_directory('./dist/', path)


@app.route('/')
def root():
  return send_from_directory('./dist/', 'index.html')

The production build from the Angular app goes directly in the dist folder. The https://domainname/ request hits the first route and actually I couldn't see the second route working. So when I type https://domainname/login it hits the first route and of course it returns 404 because there is no file with name login in the 'dist' folder. So the question is, how to route to paths like:

  • https://domainname/login
  • https://domainname/contacts
  • https://domainname/contacts/map

The other configuration that I have tried, and it has the same behavior, is using Blueprint. I don't understand why, still doesn't work with the /login path, because in this version should return the index.html file and it should work on the client side, correct? (here the angular app is build to static/dist)

main.py
from app.api_default import api as default_blueprint
app.register_blueprint(default_blueprint)

...

app/api_default/__init__.py
STATIC_FOLDER = os.path.join(os.pardir, 'static/dist')
api = Blueprint('default', __name__, static_folder=STATIC_FOLDER, static_url_path='')
from . import routes

...

app/api_default/routes.py

@api.route('/', defaults={'path': ''})
@api.route('/<path:path>')
def route_path(path):
  return api.send_static_file('index.html')


@api.route('/')
def home_paths():
  return api.send_static_file('index.html')
like image 307
makkasi Avatar asked Jan 28 '26 17:01

makkasi


1 Answers

Angular applications are single-page applications (SPA). A SPA is a web application or web site that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a server [1].

Once you have successfully served the index.html page from Flask and loaded the Angular application, routing is handled by the Angular Router.

See Routing & Navigation

like image 125
Christopher Peisert Avatar answered Jan 30 '26 12:01

Christopher Peisert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!