【问题标题】:Server rendering React app behind a URL prefix with react-router服务器使用 react-router 在 URL 前缀后面渲染 React 应用程序
【发布时间】:2015-12-08 19:13:23
【问题描述】:

我正在使用 react-router、React 0.14 和 nginx 来渲染一个通用的 JS 应用程序。因为我正在转换现有应用程序,所以我需要将新的“反应”代码放在 url 前缀后面,比如/foo

但是,理想情况下,我希望 nginx 配置将 proxy_pass 处理到在本地端口(例如 8080)上运行的反应服务器。

nginx 配置

location /foo/ {
    proxy_pass http://localhost:8080/;
    proxy_set_header Host $host;
}

反应路由器routes.jsx

import HomePage from 'components/pages/HomePage';
import AboutPage from 'components/pages/AboutPage';
import NotFoundPage from 'components/pages/NotFoundPage';

export default (
    <Route path="/">
        <IndexRoute component={HomePage} />
        <Route path="about" component={AboutPage} />
        <Route path="*" status={404} component={NotFoundPage} />
    </Route>
);

服务器上没有什么特别的。服务器端渲染似乎工作正常,但是当它到达客户端时,由于路径不匹配,它在控制台中显示以下警告:

Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
 (client) <div class="NotFoundPage" data-r
 (server) <div class="HomePage" data-react

我想这是有道理的,因为 URL 实际上是 http://localhost:80801/foo 而不是 react-router 在客户端上所期望的 http://localhost:8081/

除了将/foo 前缀放在顶级路由中之外,还有其他解决方法的想法吗?我不想这样做的原因是我不想到处都有/foo 前缀(例如在&lt;Link /&gt; 组件中)。

MTIA!

【问题讨论】:

    标签: javascript nginx reactjs react-router


    【解决方案1】:

    setting up the history object时可以配置baseURL

    import { createHistory, useBasename } from 'history'
    
    const history = useBasename(createHistory)({
      basename: '/foo'
    })
    

    【讨论】:

    • useBaseName 已从 history v4 中删除,仅供未来任何人参考。
    猜你喜欢
    • 2016-03-26
    • 2016-08-06
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2018-11-12
    • 1970-01-01
    • 2016-11-17
    相关资源
    最近更新 更多