简体   繁体   English

服务器使用React-Router在URL前缀后呈现React应用

[英]Server rendering React app behind a URL prefix with react-router

I'm using react-router, React 0.14 and nginx to render a universal JS app. 我正在使用react-router,React 0.14和nginx渲染通用JS应用程序。 Because I'm in the middle of transitioning an existing app, I need to put the new 'react' code behind a url prefix, say /foo 因为我正在过渡现有应用程序,所以需要将新的“ react”代码放在url前缀后面,例如/foo

However, I'd ideally like nginx config to handle the proxy_pass to the react server running on a local port (say 8080). 但是,理想情况下,我希望nginx config处理在本地端口(例如8080)上运行的proxy_pass Server的proxy_pass

nginx conf Nginx的配置

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

React-router routes.jsx 反应路由器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>
);

Nothing special on the server. 服务器上没有什么特别的。 The server-side rendering seems to work fine, but when it gets to the client, since the path doesn't match up it shows the following Warning in the console: 服务器端渲染似乎工作正常,但是当到达客户端时,由于路径不匹配,因此在控制台中显示以下警告:

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

Which I guess makes sense since the URL is actually http://localhost:80801/foo instead of http://localhost:8081/ which react-router is expecting on the client. 我猜这是有道理的,因为URL实际上是http://localhost:80801/foo而不是react-router在客户端上期望的http://localhost:8081/

Any ideas of ways around this other than putting the /foo prefix in the top-level Route? 除了将/foo前缀放在顶级Route之外,还有其他解决方法的想法吗? The reason I don't want to do that is I don't want to have /foo prefixes everywhere (in the <Link /> components for example). 我不想这样做的原因是,我不想到处都有/foo前缀(例如,在<Link />组件中)。

MTIA! MTIA!

You can configure a baseURL when setting up the history object . 设置历史记录对象时,可以配置baseURL

import { createHistory, useBasename } from 'history'

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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