瓶和反应路由 [英] Flask and React routing

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

问题描述



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

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

和main ($)
$ b

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

我正在使用react-router 在React应用程序,一切工作正常,react-router把我带到 / something 我得到了渲染的视图,但是当我刷新 / something 的页面时,Flask应用程序负责处理这个调用,并得到 Not Found 错误。



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

  from flask import Flask 
app = Flask(__ name__)

@ app.route('/',defaults = {'path':''})
$ app_route('/< path:path>')
def catch_all(path):
return'你想要的路径:%s'%path

如果__name__ =='__main__':
app.run()

并重新使用 Flask routing 系统将 path 与客户端路由匹配到相同的路由,以便嵌入数据客户端将在HTML响应中需要JSON。


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

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()

and the main route which leads to the React:

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

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.

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.

解决方案

We used catch-all URLs for this.

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()

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.

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

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