簡體   English   中英

React Router 部署時無法直接訪問子頁面

[英]React Router fail to direct access subpage when deployed

當我在本地主機上工作時,使用 create-react-app

我可以訪問 localhost:3000/A 或 localhost:3000/B

但是當我將它部署到服務器時, npm build run 並將構建的文件放到服務器文件夾中,就像https://ip/project_name

我可以單擊<Link/>轉到https://ip/project_name/Ahttps://ip/project_name/B但我無法直接訪問https://ip/project_name/A

應用程序.js

<BrowserRouter basename={'project_name'}>
    <Route path='/A' component={A}/>
    <Route path='/B' component={B}/>
</BrowserRouter>

關聯

<Link to="/A">A</Link>
<Link to="/B">B</Link>

包.json

"homepage": ".",
...
"dependencies": {
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.2.0"
}

您是否嘗試過使用字符串作為 basename 道具?

<BrowserRouter basename="project_name">
    <Route path='/A' component={A}/>
    <Route path='/B' component={B}/>
</BrowserRouter>

為后人:

您必須在 Web 服務器中添加重寫規則:例如,將 /* 重寫為 /index.html

它應該可以解決您的問題。

為什么:對於具有動態(反應)頁面的靜態站點,Web 服務器僅提供主文件 index.html 和一些靜態文件,如 css、圖像等。

加載 index.html 后,將使用 react-router 選擇正確的頁面,具體取決於 url 路徑上的資源路徑。

如果沒有重寫規則,像 https://ip/project_name/A 這樣的路徑會在服務器上請求一個資源“A”。 所以 index.html 永遠不會被檢索,你會得到一個 404 狀態代碼。

只需使用沒有 basename 的 HashRouter 而不是 BrowserRouter:

import { HashRouter, Route } from 'react-router-dom';

// Then in render
<HashRouter>
  <Route path='/' component={ Home } exact />
  <Route path='/contact' component={ Contact} exact />
</HashRouter>

請注意,您將 /#/ 包含在 URL 中:

http://server.com/path/#/contact

問題出在服務器文件夾中,反應路由器設置正確。

暫無
暫無

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

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