服务器端渲染与反应路由器v4

时间:2017-06-09 17:56:24

标签: reactjs express serverside-rendering react-router-v4

Following this stackoverflow post

我尝试使用react-router-v4

设置服务器渲染

我的 routes.js 文件:

var React = require('react');
import ReactDOM from 'react-dom';
import Appa from './components/app.js';
import Welcome from './components/welcome.js';
import { BrowserRouter as Router, Route,Redirect} from 'react-router-dom';

export default () =>
<Router>
  <div>
    <Route exact path="/" component={Appa} />
    <Route path="/home" component={Welcome} />
  </div>
  </Router>;

server.js

import React from 'react';
import {renderToString} from 'react-dom/server';
import { match, RoutingContext,ServerRouter, createServerRenderContext } from 'react-router';
import Routes from './app/routes.js';
var express  = require('express');
const app = express();

app.use(function(req,res,next) {
const context = createServerRenderContext();
  let markup = renderToString(
    <ServerRouter location={req.url} context={context} > <Routes /> </ServerRouter>);
  const result = context.getResult();

  if (result.redirect) {
    res.writeHead(301, {
      Location: result.redirect.pathname,
    });
    res.end();
  } else {
    if (result.missed) {
      res.writeHead(404);
      markup = renderToString(
        <ServerRouter location={req.url} context={context}> <Routes /> </ServerRouter>);
    }
    res.write(markup);
    res.end();
  }

});

app.get('*', function(req,res,next){
 
  res.sendFile(path.resolve(__dirname ,'/dist/index.html'));
   
});

每当我的应用程序路由到/ home时,需要很多时间才能加载并最终显示无法获取/ home请帮我识别代码中的错误

1 个答案:

答案 0 :(得分:0)

我很确定您的回调参数reqres已切换。回调的签名为function(req, res, next)。尝试将您的使用函数移动到app.all回调的声明之上。