簡體   English   中英

ReactJS Flask:一個網頁鏈接在本地主機上一直使用錯誤的端口5000,而不是正確的端口3000

[英]ReactJS Flask: One webpage link keeps using the wrong port 5000 on localhost instead of correct port 3000

我有一個帶有 ReactJS 前端和 Python-Flask 后端的網站,其鏈接類似於主頁 http://localhost:3000/。 我有 4 個頁面,其中 3 個頁面對 go 到 http://localhost:3000/page1 等執行正確的操作。但是,當我單擊鏈接,總是帶我去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,您的 flask 服務器將成為請求的接收者。

我也想了解你的用例。 所以你靜態地為你的 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM