尝试进入 React 应用程序路由时出现 404

Sah*_*ata 6 nodes reactjs react-router

我刚刚在 c-panel 上部署了我的 React 应用程序构建。该应用程序包括不同的路线,每次我尝试到达其中一条路线时,我都会得到404 Not found。例如,如果我尝试访问http://example.com/它,它将进入该网站,如果我按下链接到它的按钮,http://example.com/articles它将起作用。http://example.com/articles但是,如果我尝试从我共享的链接获取或仅输入此地址,我会得到404 Not found. 当我在本地主机上运行开发模式时,不会发生这种情况。

我更改了 package.json 中的主页 url "homepage": "http://example.com",,但没有效果。

我的应用程序根目录包含<Router>

function App() {
  return (
    <Provider store={store}>
      <Router>
        <React.Fragment>
          <CssBaseline />
          <Header title="exampletitle" />
          <MobileHeader />
          <Main />
          <BottomNavbar />
        </React.Fragment>
      </Router>
    </Provider>
  );
}
Run Code Online (Sandbox Code Playgroud)

这是由路由操纵的 Main.js 组件。

function Main(props) {
  return (
    <div>
      <Switch>
        <Route exact path="/" component={Homepage} />
        <Route exact path="/about" component={About} />
        <Route exact path="/signup" component={Registerpage} />
        <Route exact path="/ap" component={Adminpage} />
        <Route exact path="/signin" component={SignIn} />
        <Route exact path="/userpanel" component={UserPanelPage} />
        <Route path="/article/:category" component={Articlepage} />
        <Route path="/articlepage/:id" component={ReadArticlePage} />
      </Switch>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我当我直接通过链接输入这些页面时如何加载这些页面吗?

Aje*_*hah 8

如果您的应用程序在您使用导航时适用于所有路由<Link>,但是当您直接在浏览器中键入http://example.com以外的 URL(例如http://example.com/articleshistory.push )时抛出404 Not Found ,你需要:

通过重定向到 index.html 页面来教您的服务器处理 404 。

您可以通过以下方式之一执行此操作:

  1. 添加自定义 404 页面,将您重定向到 index.html。
  2. 如果您的托管解决方案 c-panel为部署提供错误页面设置,请提供 index.html 作为错误页面。
  3. 使用react-router中的HashRouter 。查看HashRouter 解决方案什么是 HashRouter

另外,请查看“客户端路由注释”“如何在 cPanel 上部署”


归档时间:

查看次数:

12463 次

最近记录:

4 年,8 月 前