我有一个带有API路由的Flask后端,可由使用create React app创建的React单页应用程序访问.使用create react app dev服务器时,我的Flask后端工作正常.

我想从我的Flask服务器上安装(使用npm run build个)静态React应用程序.构建React应用程序将导致以下目录 struct :

- build
  - static
    - css
        - style.[crypto].css
        - style.[crypto].css.map
    - js
        - main.[crypto].js
        - main.[crypto].js.map
  - index.html
  - service-worker.js
  - [more meta files]

[crypto]是指在构建时随机生成的字符串.

收到index.html文件后,浏览器会发出以下请求:

- GET /static/css/main.[crypto].css
- GET /static/css/main.[crypto].css
- GET /service-worker.js

我应该如何提供这些文件?我想到了这个:

from flask import Blueprint, send_from_directory

static = Blueprint('static', __name__)

@static.route('/')
def serve_static_index():
    return send_from_directory('../client/build/', 'index.html')

@static.route('/static/<path:path>') # serve whatever the client requested in the static folder
def serve_static(path):
    return send_from_directory('../client/build/static/', path)

@static.route('/service-worker.js')
def serve_worker():
    return send_from_directory('../client/build/', 'service-worker.js')

通过这种方式,可以成功地为静态assets资源 提供服务.

另一方面,我可以将其与内置的静态工具结合起来.但我不明白如何配置它.

我的解决方案足够健壮吗?有没有办法使用内置的Flask 功能来服务这些assets资源 ?有没有更好的方法来使用create react应用程序?

推荐答案

import os
from flask import Flask, send_from_directory

app = Flask(__name__, static_folder='react_app/build')

# Serve React App
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    if path != "" and os.path.exists(app.static_folder + '/' + 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)

Thats what I ended up with. So bascially catch all routes, test if the path is a file => send file => else send the index.html. That way you can reload the react app from any route you wish and it does not break.

Reactjs相关问答推荐

如何使用next.js以DOM为目标在映射中使用Ref

REACT路由DOM根据参数呈现不同的路由

我想删除NextJs中的X轴标签APEXCHARTS

TypeError:SearchProduct.get()获得了意外的关键字参数查询'

如何使用Reaction Testing Library+Vitest正确更新单元测试中的输入?

状态更改时的rtk查询触发器

更改点几何体的坐标会将其隐藏

根据用户 Select 的注册类型更改表单字段

使用以Jest 的方式返回 Promise 的方法来模拟可构造的 API 类时出现问题

在 React 中使用forwardRef时无法声明自定义属性

面临 React 模式中点击外部条件的问题

useRef 不关注模态

我可以在加载器函数中多次 fetch() 并使用一次 useloaderdata() 提取它吗?

Stripe Checkout:是否可以创建不自动续订的订阅?

条件渲染元素的测试不起作用

顶点图表甜甜圈项目边框半径

如何禁用来自 React Native API 的某些特定项目的可touch 不透明度

如何在 JSX 中使用 -webkit- 前缀?

.filter() 函数在删除函数中创建循环 - React

Material UI 安装和 React v. 18.2 出现问题