如何使用react-router 2设置服务器端渲染

时间:2016-01-25 05:25:07

标签: javascript node.js express reactjs react-router

我想将我的应用程序移植到1.0的react-router 2.0。我试图在快递上做服务器端渲染。

server.js代码(1.0)(正常工作)

var routes = require('./public/js/app.node.js');

app.get('*', function(req, res, next) {

  var location = new Location(req.path, req.query);

  try {
    Router.run(routes(), location, function(e, i, t) {
      var str = React.renderToString(
                  React.createElement(Router, i));
    });
  } catch(e) {
    return next();
  }
});

server.js code(2.0)(不工作)

var routes = require('./public/js/app.node.js');

app.get('*', function(req, res, next) {

  var location = new Location(req.path, req.query);

  try {
  match({routes, location: req.url} , function (error, redirectLocation, renderProps) {
      if (error) {
        res.status(500).send(error.message);
      } else if (redirectLocation) {
        res.redirect(302, redirectLocation.pathname + redirectLocation.search);
      } else if (renderProps) {
        var str = renderToString(React.createElement(RoutingContext, renderProps));
        res.status(200).send(str);
      } else {
        res.status(404).send('Not found');
      }
  });
}

routes.jsx:

  export default (withHistory, onUpdate) => {

  return (
    <Provider store={store}>
      <Router history={history} onUpdate={onUpdate}>
        <Route path='/' component={BarcodeListing} />
      </Router>
    </Provider>
  );
};

上述代码与/不符。这是为什么。 console.log(req.url)给了我/,然后路由中的/应该与req.url中的/匹配!!

0 个答案:

没有答案