1- var express = require ( 'express' )
2- var path = require ( 'path' )
3- var compression = require ( 'compression' )
1+ import express from 'express'
2+ import path from 'path'
3+ import compression from 'compression'
4+ import React from 'react'
5+ import { renderToString } from 'react-dom/server'
6+ import { match , RouterContext } from 'react-router'
7+ import routes from './modules/routes'
48
59var app = express ( )
610
@@ -10,10 +14,34 @@ app.use(compression())
1014app . use ( express . static ( path . join ( __dirname , 'public' ) ) )
1115
1216// send all requests to index.html so browserHistory works
13- app . get ( '*' , function ( req , res ) {
14- res . sendFile ( path . join ( __dirname , 'public' , 'index.html' ) )
17+ app . get ( '*' , ( req , res ) => {
18+ match ( { routes, location : req . url } , ( err , redirect , props ) => {
19+ if ( err ) {
20+ res . status ( 500 ) . send ( err . message )
21+ } else if ( redirect ) {
22+ res . redirect ( redirect . pathname + redirect . search )
23+ } else if ( props ) {
24+ // hey we made it!
25+ const appHtml = renderToString ( < RouterContext { ...props } /> )
26+ res . send ( renderPage ( appHtml ) )
27+ } else {
28+ res . status ( 404 ) . send ( 'Not Found' )
29+ }
30+ } )
1531} )
1632
33+ function renderPage ( appHtml ) {
34+ return `
35+ <!doctype html public="storage">
36+ <html>
37+ <meta charset=utf-8/>
38+ <title>My First React Router App</title>
39+ <link rel=stylesheet href=/index.css>
40+ <div id=app>${ appHtml } </div>
41+ <script src="/bundle.js"></script>
42+ `
43+ }
44+
1745var PORT = process . env . PORT || 8080
1846app . listen ( PORT , function ( ) {
1947 console . log ( 'Production Express server running at localhost:' + PORT )
0 commit comments