我目前的文件夹结构如下:
/
--client
----dist
------index.html
------index.js
--server
----server.py
dist/ 中的 index.js 服务于 React 应用程序。我的 server.py 看起来像这样:
import os
from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route('/')
def hello_world():
return send_from_directory('../client/dist/', 'index.html')
if __name__ == "__main__":
app.run()
不幸的是,这没有用,我得到了一个Failed to load resource。我查看了关于 SO 及其他关于此的几篇文章。它们中的大多数都非常陈旧(也许已经过时),并且它们通常都具有不同的文件夹结构,其中 index.html 文件是从 static 文件夹中提供的 server/ 或类似的东西。
我真的只是想做我认为应该是一件容易的事:当 localhost:5000 被访问时,Flask 服务于 ../client/dist/index.html 从那里 React 接管并做它的事情。
如果有人能为我提供实现目标的最小/干净方法,我将不胜感激。
请您参考如下方法:
事实证明我有点错了。我以为这个问题不是转贴,但经过更多搜索后,我发现了另一个与我非常相似的 StackOverflow 问题:
Serving static html file from another directory from flask restful endpoint
将那里和其他地方的几个答案放在一起,我有一个最小的工作解决方案:
from flask import Flask, send_from_directory
app = Flask(__name__, static_folder='../client/dist')
@app.route('/')
def hello_world():
return send_from_directory(app.static_folder, 'index.html')
if __name__ == "__main__":
app.run()
当我现在访问 localhost:5000 时,我得到了 index.html 的内容。
