javascript - 服务器在带有 react-router 的 URL 前缀后面渲染 React 应用程序

标签 javascript nginx reactjs react-router

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

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

nginx 配置

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

React 路由器 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/哪个 react-router 期待客户端。

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

MTIA!

最佳答案

setting up the history object 时,您可以配置一个 baseURL .

import { createHistory, useBasename } from 'history'

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

关于javascript - 服务器在带有 react-router 的 URL 前缀后面渲染 React 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34164103/

相关文章:

javascript - AngularUI DatePicker - JavaScript - 获取 SQL 日期格式时休息一天

ruby-on-rails - Puma 和 Nginx 502 Bad Gateway 错误(Ubuntu 服务器 14.04)

node.js - 基本身份验证和 JWT

reactjs - 如何声明一个全局变量并在 ReactJS 的所有其他模块中访问它?

javascript - 构造函数内的循环有什么问题? [JS]

javascript - 立即调用匿名函数的两种方式(function(d){ }() );和 (函数(x){ } )();

javascript - react 真的需要前端 ENV 上的 nodeJS 吗?

node.js - Nginx 重定向到 Node.js 后端

javascript - 用于将具有相同键和值的 React props 传递给组件的语法糖

css - CSS Flexbox系统中的xs,md,lg是什么意思?