简体   繁体   中英

React Router fail to direct access subpage when deployed

When I am working in localhost, using create-react-app

I am able to access localhost:3000/A or localhost:3000/B

But when I deploy it to the server, npm build run and put the built file to the server folder like to the https://ip/project_name

I can click in the <Link/> to go to https://ip/project_name/A or https://ip/project_name/B but I cannot direct access to https://ip/project_name/A .

App.js

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

Link

<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"
}

Have you tried with string for basename prop?

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

For posterity :

You have to add a rewrite rule in your web server : For example, Rewrite /* as /index.html

It should solve your problem.

Why : For static site with dynamic (react) pages, the web server serves the main file index.html only and some static files like css, images, etc.

Once index.html is loaded, react-router is then used to select the correct page, depending on the resource path on the url path.

If there is no rewrite rule, a path like https://ip/project_name/A request a resource 'A' on the server. So index.html is never retrieved and you get a 404 status code.

Just use HashRouter without basename instead of BrowserRouter:

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

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

Note that you'll have /#/ included in URLs:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM