【问题标题】:Express 404 page overlaps the react routerExpress 404 页面与反应路由器重叠
【发布时间】:2017-03-11 19:00:16
【问题描述】:

你好

我有一个 express 应用程序作为 REST 服务器运行,这意味着所有 /api/xx 路由都在 express 中处理。

我还有一个 react 应用程序(在访问 / 时由 express 提供服务)作为客户端,它也有一个路由器,当我刷新 react route 时出现问题,反而出现了 express 的 404 页面错误反应页面本身。

反应路由器

<Router history={browserHistory}>
  <Route path="/" component={MainLayout} user={user}>
    <IndexRoute component={DocumentsPage}></IndexRoute>
      <Route path="about" component={AboutPage}></Route>
      <Route path=":id/preview" component={PreviewPage}/>
      <Route path="upload" component={UploadPage}></Route>
  </Route>
</Router>

当我使用&lt;Link to="upload" &lt;/Link&gt; 访问时,页面出现,当我刷新页面时,我得到了 404 express 的页面..

任何帮助都会很可爱

【问题讨论】:

    标签: express reactjs routes react-router


    【解决方案1】:

    您需要配置回退,以便您的 Express 路由中不存在的每个请求都被重定向到您的 React 应用程序/。下面是一个基本示例,说明如何使用 Express 做到这一点:

    import fallback from 'express-history-api-fallback';
    import express from 'express';
    import http from 'http';
    
    // Set up express
    const app = express();
    const server = http.createServer(app);
    const root = `${__dirname}`;
    
    // History Fallback for express
    app.use(express.static(root));
    app.use(fallback('index.html', { root }));
    
    // Listen
    server.listen(8080, '0.0.0.0');
    

    那么你也可以使用 React Router 处理你的 404 页面。

    【讨论】:

    • 看起来像我想要的,但无法使其与位于 ./public/index.html 的 index.html 一起使用,我如何编辑后备行以使用我的 index.html ?谢谢
    • 更改根文件夹,这一行:const root = `${__dirname}/public`;
    猜你喜欢
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 2021-01-22
    • 2017-11-10
    • 1970-01-01
    • 2015-06-30
    相关资源
    最近更新 更多