Search code examples
pythonreactjsflaskcreate-react-app

Unable to render create-react-app boilerplate views from Flask backend


I'm having a hard time integrating create-react-app single page application to my flask backend. I want to be able to make a fetch/axios call from my front end like so: axios.get('/getResults') and fetch('/getResults'). Some things I have tried but not limited to is specifying the Flask port as 3000 which is the same used by create-react-app. Also, used the proxy configuration feature on the "package.json" file of create-react-app but to no avail. I suspect my folder structure and Flask code implementation may likely be causing this. Below is my folder structure and "app.py" code. Any help I could get will be appreciated. I can provide additional information if necessary. Thanks

Project
-build(contains static folder, index.html...Other meta files)
-node_modules
-public
-src
app.py
package.json
requirements.txt

app.py:

from flask import Flask, Response, request, jsonify, make_response, send_from_directory,render_template

app = Flask(__name__, static_path='/build/static/')
app.debug=True

@app.route('/')
def root():
    print('Inside root function')
    return app.send_static_file('index.html')

@app.route('/getResults', methods=["GET"])
def results():
    print('Inside getResults path')
    return app.send_static_file('index.html')

@app.route('/postData', methods=["POST"])
def data_results():
    print('Inside postData path')
    data = request.get_json
    return jsonify(data)

@app.route('/<path:path>')
def send_js(path):
    print("inside send_js fxn")
    return send_from_directory('./build/static',path)


if __name__ == "__main__":
    print("inside main host call")
    app.run(host='0.0.0.0', port=3000)

Errors I get when I run "python app.py" are:

On the terminal: Inside root function 127.0.0.1 - - [12/Jun/2017 09:42:24] "GET / HTTP/1.1" 404 -

On the browser:Not Found - The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.


Solution

  • I was having the exact same issue and I was able to solve it by appeasing Flask with symlinks.

    Keep the templates and static directory paths at their defaults and in the directory with your Flask main file, add these symlinks

    ln -s build/ templates
    ln -s build/static static
    

    In case you were curious, this was my specific problem, which just involved a few more nested directories but was in essence the same:

    Running NPM Build from Flask

    You can then use Nurzhan's root configuration:

    @app.route('/')
    def root():
        print('Inside root function')
        return render_template('index.html')
    

    But you only require your app declaration to be: app = Flask(__name__)

    The only thing that doesn't work for me is the favicon, and I will update this answer once I figure that out.