我正在尝试为我的react应用程序设置服务器端呈现,并且我正在尝试使用伟大的react-router模块来允许它处理非js情况(一些爬虫,当用户有js由于某种原因关闭了)。但是,我遇到了麻烦。我一直在使用https://stackoverflow.com/a/28558545/3314701这个很好的回答作为各种指导,但是我发现了一些奇怪的错误。在尝试使用Syntax Error
时,我获得了持久性react.renderToString()
。我是否错误地设置了服务器端渲染,缺少明显的东西,或其他任何东西?
我的设置:
真正基本的Express服务器
require('babel/register');
var app = express();
// misc. express config...
var Router = require('react-router'),
routes = require('../jsx/app').routes,
React = require('react');
app.use(function(req, res, next) {
var router = Router.create({location: req.url, routes: routes});
router.run(function(Handler, state) {
console.log(Handler);
var html = React.renderToString(<Handler/>);
return res.render('react_page', {html: html});
});
});
顶级反应<App/>
组件
// Shims
require('intl');
require('es5-shim');
var React = require('react/addons'),
Router = require('react-router'),
Nav = require('./nav'),
injectTapEventPlugin = require("react-tap-event-plugin"),
window.React = React; // export for http://fb.me/react-devtools
// Intl
var ReactIntl = require('react-intl'),
IntlMixin = ReactIntl.IntlMixin;
var Route = Router.Route,
DefaultRoute = Router.DefaultRoute,
NotFoundRoute = Router.NotFoundRoute,
RouteHandler = Router.RouteHandler;
var App = React.createClass({
mixins: [IntlMixin],
getInitialState: function() {
return {
connected: false,
loaded: false,
user: true
};
},
render: function() {
return (
<div className="container-fluid">
<Nav/>
<RouteHandler/>
<Footer/>
</div>
);
}
});
var routes = (
<Route name="Home" path="/" handler={App}>
<DefaultRoute name="Welcome " handler={Welcome}/>
<Route name="Bar" path="/bar" handler={Bar}>
<Route name="foo" path="/foo" handler={Foo}></Route>
</Route>
);
Router.run(routes, Router.HistoryLocation , function(Handler) {
React.render(<Handler/>, document.getElementById('app'));
});
module.routes = routes;
输出:
flo-0,1,2 (err): <div className="progressbar-container" >
flo-0,1,2 (err): ^
flo-0,1,2 (err): SyntaxError: Unexpected token <
flo-0,1,2 (err): at exports.runInThisContext (vm.js:73:16)
flo-0,1,2 (err): at Module._compile (module.js:443:25)
flo-0,1,2 (err): at Module._extensions..js (module.js:478:10)
flo-0,1,2 (err): at Object.require.extensions.(anonymous function) [as .js] (/Users/user/Code/foobar/apps/flo/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:161:7)
flo-0,1,2 (err): at Module.load (module.js:355:32)
flo-0,1,2 (err): at Function.Module._load (module.js:310:12)
flo-0,1,2 (err): at Function.<anonymous> (/Users/user/.nvm/versions/node/v0.12.4/lib/node_modules/pm2/node_modules/pmx/lib/transaction.js:62:21)
flo-0,1,2 (err): at Function.cls_wrapMethod (/Users/user/Code/foobar/apps/bar/node_modules/newrelic/lib/shimmer.js:230:38)
flo-0,1,2 (err): at Function.<anonymous> (/Users/user/Code/foobar/apps/bar/node_modules/pmx/lib/transaction.js:62:21)
flo-0,1,2 (err): at Module.require (module.js:365:17)
flo-0,1,2 (err): at require (module.js:384:17)
答案 0 :(得分:39)
所以,我最终自己解决了这个问题。我得到的错误来自一个未渲染的嵌套组件,这就是js引擎抱怨随机<
字符的原因。
现在到我的快递设置。对于那些不知道如何将反应用于服务器端渲染的人来说,它非常简单:Node或io.js可用于在组件上调用React的renderToString()
方法,然后将其发送到请求客户。您可能已经听说过这种方法带来的好处,但对于那些不知道的人:
你可能会对这种方法感到疯狂,并在加载时处理应用程序的占位符或为缓慢加载状态(在加载时加载Facebook)提供其他反馈机制。
基本方法大致按以下方式运作:
routes.jsx
req.path
为react-router提供路由字符串来处理。routes.jsx
文件接管并从此处生成带react-router
的html。这里的另一个好处是您的应用程序代码可以被缓存,未来的交互有望甚至不必依赖于另一个调用。 还有一点值得注意:我使用webpack捆绑我的反应代码,现在browser.jsx
是入口点。在重构服务器端渲染之前,它是app.jsx
;您可能需要重新配置您的结构以适应在何处呈现的内容。 :)
代码:
<强> Browser.jsx 强>
const React = require('react');
const Router = require('react-router').Router;
const hist = require('history');
const routes = require('./routes');
const newHistory = hist.createHistory();
React.render(<Router history={newHistory}>{routes}</Router>, window.document);
App.js(快递服务器):
//...other express configuration
const routes = require('../jsx/routes');
const React = require('react');
const {RoutingContext, match} = require('react-router');
const hist = require('history');
app.use((req, res, next) => {
const location = hist.createLocation(req.path);
match({
routes: routes,
location: location,
}, (err, redirectLocation, renderProps) => {
if (redirectLocation) {
res.redirect(301, redirectLocation.pathname + redirectLocation.search);
} else if (err) {
console.log(err);
next(err);
// res.send(500, error.message);
} else if (renderProps === null) {
res.status(404)
.send('Not found');
} else {
res.send('<!DOCTYPE html>' + React.renderToString(<RoutingContext {...renderProps}/>));
}
});
});
//...other express configuration
<强> Routes.jsx 强>
<Route path="/" component={App}>
<DefaultRoute component={Welcome}/>
<Route path="dashboard" component={Dashboard}/>
<Route path="login" component={Login}/>
</Route>
<强> App.jsx 强>
<html>
<head>
<link rel="stylesheet" href="/assets/styles/app.css"/>
</head>
<body>
<Navigation/>
<RouteHandler/>
<Footer/>
<body/>
</html>
有用的链接: