简体   繁体   中英

Serving a create-react-app with Flask "Uncaught SyntaxError: Unexpected token <"

I'm building a web app with react-create-app and want to serve it using flask. the frontend is generated using

npx create-react-app frontend
cd frontend
npm run build

my project structure looks like this:

- backend
    - static
    - templates
    - app.py
- frontend
    - build
        - static
            - css
                ...
            - js
                ...
            - media
                ...
        - favico.ico
        - index.html
        - service-worker.js
        - ...
    - public
        ...
    - src
        ...
    - ...

app.py

from flask import Flask, send_from_directory
import os


app = Flask(__name__, static_folder=r'..\frontend\build')


@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    if path != "" and os.path.exists("/static/" + path):
        return send_from_directory(app.static_folder, path)
    else:
        return send_from_directory(app.static_folder, 'index.html')


if __name__ == '__main__':
    app.run(use_reloader=True, port=5000, threaded=True, debug=True)

if I'm running serve -s build the app runs and everything is fine. however, running python app.py shows a blank page and chromes console shows the following errors:

Uncaught SyntaxError: Unexpected token < 2.b41502e9.chunk.js:1
Uncaught SyntaxError: Unexpected token < main.4001340c.chunk.js:1 
Manifest: Line: 1, column: 1, Unexpected token. :5000/manifest.json:1

It looks like the browser can't interpret the jsx syntax. how can I fix this issue?

你安装了 Flask 吗?

npm install flask

Having just solved this myself, it's actually that you're actually serving the index.html for all requests. So *chunk.js is html, not Javascript so you get a syntax error.

This is because the following:

if path != "" and os.path.exists("/static/" + path):

is always false. /static/ is not a meaningful path in this context.

Change it to:

if path != "" and os.path.exists(f"{app.static_folder}/{path}"):

and it'll work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM