反应路由器服务器端意外行为

时间:2016-11-01 19:45:05

标签: node.js express reactjs

我是以下server.js:

import express from 'express';
import path from 'path';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import routes from './src/client/app/config/routes.jsx';

let port = process.env.PORT || 8080;
let app = express();

app.use(express.static('src/client/'));

// app.get('/', (req, res) => {
//  res.sendFile(path.resolve(__dirname + '/src/client/index.html'))
// });

app.get('*', (req, res) => {
  match(
    { routes, location: req.url },
    (err, redirectLocation, renderProps) => {

      // in case of error display the error message
      if (err) {
        return res.status(500).send(err.message);
      }

      // in case of redirect propagate the redirect to the browser
      if (redirectLocation) {
        return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
      }

      // generate the React markup for the current route
      let markup;
      if (renderProps) {
        // if the current route matched we have renderProps
        markup = renderToString(<RouterContext {...renderProps}/>);
      } 
      // else {
      //   // otherwise we can render a 404 page
      //   markup = renderToString(<NotFoundPage/>);
      //   res.status(404);
      // }

      // render the index template with the embedded React markup
      return app.use(express.static(path.join(__dirname + '/src/client/index.html')));
    }
  );
});

app.listen(port);
console.log('server started');

routes.jsx

import React from 'react';
import { Route, Router, browserHistory } from 'react-router';
import ReactDOM from 'react-dom';

import Wrapper       from './../components/wrapper.jsx';
import Home          from './../components/home.jsx';
import Projects      from './../components/projects.jsx';
import SingleProject from './../components/projectContent/singleProject.jsx';
import About         from './../components/aboutUs.jsx'

if(typeof window !== 'undefined') {
    console.log('here baby');
    ReactDOM.render((
        <Router history={browserHistory} >
            <Route component={Wrapper} >
                <Route path="/" component={Home} />
                <Route path="projects" component={Projects} />
                <Route path="projects/:id" component={SingleProject} />
                <Route path="about" component={About} />
            </Route>
        </Router>
    ), document.getElementById('app'));

我可以在localhost:8080 /访问我的应用程序但是当我手动刷新浏览器时,它会进入无限循环而不会完全刷新页面。由于服务器端实现,我期待刷新浏览器将正常工作。

如果我改变

app.get('*', (req, res) => {

app.get('/', (req, res) => {

当我刷新页面时,我得到“无法得到......”

1 个答案:

答案 0 :(得分:0)

你在app.use()内部返回app.get(),这可能会导致你的无限循环。您应该呈现由renderToString()生成的标记:

...
// render the index template with the embedded React markup
return res.render('index', { markup: markup });