Flask 和 React 路由

Flask and React routing

我正在使用 React 构建 Flask 应用程序,但最终遇到了路由问题。

后端负责成为 API,因此一些路由看起来像:

@app.route('/api/v1/do-something/', methods=["GET"])
def do_something():
    return something()

以及通往 React 的主要路线:

@app.route('/')
def index():
    return render_template('index.html')

我在 React 应用程序中使用 react-router,一切正常,react-router 将我带到 /something 并获得渲染视图,但是当我在 [= 上刷新页面时12=] 然后 Flask 应用程序负责这个调用,我得到 Not Found 错误。

最好的解决方案是什么?我正在考虑将所有未调用 /api/v1/... 的调用重定向到 / 这并不理想,因为我将返回我的应用程序的主页,而不是呈现 React 视图。

为此我们使用了 catch-all URLs

from flask import Flask
app = Flask(__name__)

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return 'You want path: %s' % path

if __name__ == '__main__':
    app.run()

您还可以更进一步,重新使用 Flask routing 系统将 path 匹配到与客户端相同的路由,这样您就可以将客户端需要的数据嵌入到内部 JSON HTML 响应。

也许作为对之前答案的延伸。这为我解决了问题:

from flask import send_from_directory

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
     path_dir = os.path.abspath("../build") #path react build
     if path != "" and os.path.exists(os.path.join(path_dir, path)):
         return send_from_directory(os.path.join(path_dir), path)
     else:
         return send_from_directory(os.path.join(path_dir),'index.html')

出于某种原因,包罗万象的 URL 对我不起作用。我发现使用 flask 404 处理程序会产生完全相同的结果。它看到 url 并将其向下传递以在路由器将处理它的位置做出反应。

@app.errorhandler(404)   
def not_found(e):   
  return app.send_static_file('index.html')

只是为了通知处理错误 404,render_template 非常适合我。

@app.errorhandler(404)
def not_found(e):
    return render_template("index.html")

我必须结合使用 catch-all 和 404 处理程序才能正常工作。我在一个子路径中托管一个 react-app,它有自己的来自 react-router.

的重定向处理程序
@app.route('/sub-path',  defaults={'path': 'index.html'})
@app.route('/sub-path/<path:path>')
def index(path):
    return send_from_directory('../react-dir/build', path)

@app.errorhandler(404)
def not_found(e):
  return send_from_directory('../react-dir/build','index.html')