Flask和React路由

kno*_*ody 32 python url-routing flask reactjs

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

后端负责成为API,因此有些路由如下:

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

以及通往React的主要途径:

@app.route('/')
def index():
    return render_template('index.html')
Run Code Online (Sandbox Code Playgroud)

我在React应用程序中使用react-router,一切正常,反应 - 路由器带我到/something我得到渲染的视图,但是当我刷新页面/something然后Flask应用程序负责这个调用,我得到Not Found错误.

什么是最好的解决方案?我在想重定向这是不是要求所有的呼叫/api/v1/.../它的效果并不理想,因为我将回到我的应用程序,而不是渲染的主页阵营视图.

Dan*_*mov 34

我们使用了catch-all URL.

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()
Run Code Online (Sandbox Code Playgroud)

您还可以加倍努力并重复使用Flask routing系统来匹配path与客户端相同的路由,这样您就可以将客户端需要的数据嵌入到HTML响应中作为JSON.

  • @shangyeshen在catch-all之前注册API路由,因此它们具有优先权. (6认同)
  • 找到了。我无法弄清@ app.route('/ &lt;path:path&gt;')`上的任何内容,直到我弄清楚记录不充分的Flask参数。设置`static_url_path =“”是错误的。我最后以“ static_url_path =“ / public”,static_folder =“ ../ public”`结束。然后我返回一个静态:带有硬编码的“ /public/...”URL的“ return app.send_static_file(“ index.html”)`。另外,请查看:https://www.reddit.com/r/reactjs/comments/42pn95/reactrouter_and_flask_404/(不是我)。 (2认同)

Hen*_*rik 5

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

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')
Run Code Online (Sandbox Code Playgroud)