【问题标题】:Getting 404 error if i am navigating to any URL other than homepage URL with react-router如果我使用 react-router 导航到主页 URL 以外的任何 URL,则会出现 404 错误
【发布时间】:2018-08-25 22:40:30
【问题描述】:

我的 routes.js 为

import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom';

  <Router>
    <div>
      <Route exact path="/" component={login}/>
      <Route path="/calculator" component={calculatorPage}/>
      <Route path="/result" component={resultPage}/>
    </div>
  </Router>

我已经在服务器上提升了应用程序,当我尝试使用 /calculator 输入 URL 时,我收到 404 错误。如果我使用主页 URL 到计算器页面,它可以正常工作。如果我直接输入,则会收到 404 错误。

在我当地,一切正常。即使我直接输入 /calculator ,我也会得到页面。

【问题讨论】:

  • 您的应用程序前面有什么? nginx?阿帕奇?无论如何,您需要确保 all 路径服务于您的 index.html 是什么
  • @TylerSebastian,它的 apache,悬挂在 windows 机器上。无论如何,在我的本地一切正常,即使直接在 URL 中输入计算器。但不在服务器中。
  • 正确,因为在本地,您可能正在运行 webpack dev-server 和 history-api-fallback 之类的东西,您需要将 apache 配置为始终为您的 index.html 提供服务。看到类似askubuntu.com/questions/484986/…
  • 如果你想在生产模式下部署你的应用&&刷新你的URL,你必须寻找server side rendering
  • @Atulkumarsingh Tyler 说得对。您的 Apache 服务器不知道 /calculator/result,因此您需要指示它将所有请求重写为 index.html,然后在前端,这些请求将匹配到正确的 React 路由。

标签: reactjs redux react-router react-redux react-router-v4


【解决方案1】:

.htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteBase /<YOUR_BASE_URL_HERE>/
RewriteRule ^(.*) index.html [NC,L]

【讨论】:

    猜你喜欢
    • 2016-12-14
    • 2021-04-24
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多