部署后,React Router无法直接访问子页面

时间:2020-01-17 03:17:31

标签: reactjs routes react-router web-deployment webdeploy

在localhost中工作时,请使用create-react-app

我能够访问localhost:3000 / A或localhost:3000 / B

但是,当我将其部署到服务器时,运行npm build并将生成的文件放入服务器文件夹中,就像https://ip/project_name

我可以单击<Link/>转到https://ip/project_name/Ahttps://ip/project_name/B 但我无法直接访问https://ip/project_name/A

App.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>

package.json

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

3 个答案:

答案 0 :(得分:0)

您是否尝试过使用字符串作为基本名称道具?

{
    "compilerOptions": {
         "lib": ["esnext", "dom"],
          "sourceMap": true, 
          "outFile": "./",
          "outDir": "./dist",  
          "strictFunctionTypes": true,
          "strictBindCallApply": true,
          "noImplicitThis": true,                
          "alwaysStrict": true, 
          "skipLibCheck": true,  
          "esModuleInterop": true
    }
}

答案 1 :(得分:0)

问题出在服务器文件夹中,反应路由器设置正确。

答案 2 :(得分:0)

只需使用没有 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