服务器在带有React路由器的URL前缀后面呈现React应用程序

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

本文关键字:React 应用程序 前缀 路由器 服务器 URL      更新时间:2023-09-26

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

然而,理想情况下,我希望nginx-config将proxy_pass处理到运行在本地端口(比如8080)上的react服务器。

nginx-conf

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,而不是反应路由器在客户端上期望的http://localhost:8081/

除了在顶级路由中添加/foo前缀之外,还有什么办法可以解决这个问题吗?我不想这样做的原因是,我不想到处都有/foo前缀(例如,在<Link />组件中)。

MTIA!

您可以在设置历史对象时配置baseURL

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