javascript - ReactJS Flask:一个网页链接一直在本地主机上使用错误的端口 5000 而不是正确的端口 3000
问题描述
我有一个带有 ReactJS 前端和 Python-Flask 后端的网站,其链接类似于主页 http://localhost:3000/。我有 4 个页面,其中 3 个页面执行正确的操作以转到 http://localhost:3000/page1 等。但是,当我单击 4 个页面之一(下例中的 /sea)时链接,总是带我去http://localhost:5000/sea,肯定是找不到。我可以手动将 5000 更改为 3000 并且页面运行良好,但我不确定究竟是什么导致我单击的四个链接之一使用端口 5000 而不是 3000。我访问 3 个网站的所有代码都是相同。这是 App.js 文件:
<div>
<BrowserRouter>
<Navigation/>
<Switch>
<Route path="/villagers" component={Villagers}/>
<Route path="/songs" component={Songs}/>
<Route path="/sea" component={Sea}/>
<Route path="/seadetail" component={SeaMuseum}/>
<Route path="/" component={FrontPage}/>
</Switch>
</BrowserRouter>
</div>
至于 python Flask 后端 main.py"
@app.route('/')
@app.route('/villagers/')
@app.route('/songs/')
@app.route('/sea/')
@app.route('/seadetail/')
def index():
return app.send_static_file('index.html')
解决方案
exact
除非您打算使用某些路由参数,否则您应该这样做。
<Route exact path='/sea' component={Sea} />
也可能是您的 package.json 将“主页”设置为“http://localhost:5000”或“代理”设置为“http://localhost:5000”(如果它们已被删除,您应该删除它们)放)
你做到了<a href="/sea">Hey go to sea</a>
我建议你使用
import { Link } from 'react-router-dom';
and <Link to='/sea'>Click to go to Sea</Link>
另外,我假设您在这里使用的是 create-react-app。您的 create-react-app 的开发服务器在端口 3000 上运行。因此,如果您将用户定向到 localhost:5000/sea,您的烧瓶服务器将成为请求的接收者。
我也想了解你的用例。所以你静态地为你的 create-react-app 的 public/index.html 文件提供服务?我认为您应该首先构建您的反应应用程序并提供 build/index.html 文件
沿着这些思路
app = Flask(__name__, static_folder='project/build')
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
if path != '' and os.path.exists(app.static_folder + '/' + path):
return send_from_directory(app.static_folder, path)
return send_from_directory(app.static_folder, 'index.html')
if __name__ == '__main__':
app.run(use_reloader=True, port=5000, threaded=True)
推荐阅读
- xml - 使用 Powershell 忽略 XML 文档中的命名空间
- java - java io FileNotFoundException
- r - 使用 geom_circle 修复边界效果
- php - 如何正确显示数据库中的图像?
- react-native - EXPO:未捕获的错误:未定义不是对象(评估's.STANDARD_EVENT_ADD_TO_CART')
- javascript - 在页面的特定部分添加块
- php - 获取数组中的最小值并包含重复项
- java - 在 For each 中使用 Lambda 和 Streams 并返回结果
- wordpress - 致命错误:无法在 wordpress 网站的写入上下文中使用函数返回值
- mysql - 有没有办法使用 python 脚本向托管数据库发送/插入值?