服务器在带有 react-router 的 URL 前缀后面渲染 React 应用程序 [英] Server rendering React app behind a URL prefix with react-router

查看:50
本文介绍了服务器在带有 react-router 的 URL 前缀后面渲染 React 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using react-router, React 0.14 and nginx to render a universal JS app. 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

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

However, I'd ideally like nginx config to handle the proxy_pass to the react server running on a local port (say 8080).

nginx 配置

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

React-router routes.jsx

React-router 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

我认为这是有道理的,因为 URL 实际上是 http://localhost:80801/foo 而不是 react-router 的 http://localhost:8081/期待客户.

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.

除了将 /foo 前缀放在顶级路由中之外,还有其他解决方法的想法吗?我不想这样做的原因是我不想在任何地方都有 /foo 前缀(例如在 组件中).

Any ideas of ways around this other than putting the /foo prefix in the top-level 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).

MTIA!

推荐答案

你可以在 设置历史对象.

You can configure a baseURL when setting up the history object.

import { createHistory, useBasename } from 'history'

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

这篇关于服务器在带有 react-router 的 URL 前缀后面渲染 React 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆