Flask 和 React 路由 [英] Flask and React routing

查看:30
本文介绍了Flask 和 React 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building the Flask app with React, I ended up having a problem with routing.

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

The backend is responsible to be an API, hence some routes look like:

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

以及通往 React 的主要路线:

and the main route which leads to the React:

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

我在 React 应用程序中使用 react-router,一切正常,react-router 带我到 /something 并且我得到了渲染视图,但是当我在 /something 上刷新页面时,Flask 应用程序会处理这个调用,我得到 Not Found 错误.

I'm using react-router in the React app, everything works fine, react-router takes me to /something and I get the rendered view, but when I refresh the page on /something then Flask app takes care of this call and I get Not Found error.

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

What is the best solution? I was thinking about redirecting all calls which are not calling /api/v1/... to / it's not ideal as I will get back the home page of my app, not rendered React view.

推荐答案

我们使用了 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 路由 系统将 path 匹配到与客户端相同的路由,这样您就可以将客户端需要的数据嵌入为 JSON在 HTML 响应中.

You can also go an extra mile and reuse the Flask routing system to match path to the same routes as client so you can embed the data client will need as JSON inside the HTML response.

这篇关于Flask 和 React 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆