Python (Flask) serving Angular project's index.html file

前端 未结 3 508
后悔当初
后悔当初 2021-01-05 15:30

Does anyone know how to serve an Angular single page application using Flask?

I\'m having trouble serving the default route, \'/\', which should load index.html and

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-05 15:55

    This is an old question but accepted answer did not work for me. So here is my solution that works with angular routing:


    My folder structure:

    /angular
        /src
        angular.json
        ... angular project files
    /public
        index.html
        ... angular build files
    /venv
    server.py
    

    In my angular.json I changed outputPath to achive above structure:

    "outputPath": "../public"
    

    And in server.py:

    import os.path
    
    @app.route("/custom-endpoint")
    def custom_endpoint_handler():
        return jsonify(myKey="myValue")
    
    
    # Serving static files
    @app.route('/', defaults={'path': ''})
    @app.route('/')
    @app.route('/')
    def static_proxy(path):
        if os.path.isfile('public/' + path):
            # If request is made for a file by angular for example main.js
            # condition will be true, file will be served from the public directory
            return send_from_directory('public', path)
        else:
            # Otherwise index.html will be served,
            # angular router will handle the rest
            return app.send_static_file("index.html")
    

    Footnote: I am new to flask. So any improvements or fixes if there are any errors are welcomed.

提交回复
热议问题