如何使用Next.js服务MPA前端和SSR后端?

d7v8vwbk  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(154)

我最近买了一个MUI模板。我使用React和Next.js以及Flask作为我的后端。MUI模板是多页应用程序。我曾经使用Flask作为SPA,在此之前我只需要return send_from_directory('./static/', 'index.html')一次,这样我就可以从前端服务静态文件。我猜我不应该像下面这样为Flask中的每个路由返回html页面:

  1. @app.route('/')
  2. def index():
  3. return render_template('home.html')
  4. @app.route('/login')
  5. def login():
  6. return render_template('login.html')
  7. @app.route('/signUp')
  8. def login():
  9. return render_template('signUp.html')
  10. @app.route('/home')
  11. def login():
  12. return render_template('home.html')

字符串
如何将MPA模板与我的SSR后端Flask结合?如何配置Next.js来实现这一点?这是模板包含的内容:


的数据
我试着这样写我的Flask代码,但它似乎并不好用:

  1. from flask import Flask, send_from_directory
  2. app = Flask(__name__)
  3. @app.route("/")
  4. def serve_nextjs():
  5. return send_from_directory("./static", "index.html")
  6. # Serve the static Next.js files (CSS, JavaScript, images, etc.)
  7. @app.route("/<path:filename>")
  8. def serve_static(filename):
  9. print(filename)
  10. if '/' in filename:
  11. print("1")
  12. return send_from_directory("./static", filename)
  13. else:
  14. print("goto2")
  15. return send_from_directory(f"./static/{filename}")
  16. if __name__ == "__main__":
  17. app.run(debug=True)

9nvpjoqh

9nvpjoqh1#

事实证明,这可以通过以下方式简化:

  1. @app.route('/<path:path>', methods=["GET", "POST"])
  2. def serve_page(path):
  3. return send_from_directory(f'./static/{path}', "index.html")

字符串
此外,如果您在不同的位置有静态文件,则可以这样指定它们:

  1. @app.route('/_next/<path:filename>', methods=["GET", "POST"])
  2. def next_static_files(filename):
  3. return send_from_directory(app.static_folder + '/_next/', filename)
  4. @app.route('/assets/<path:filename>', methods=["GET", "POST"])
  5. def assets_files(filename):
  6. return send_from_directory(app.static_folder + '/assets/', filename)

展开查看全部

相关问题