1+ import React from 'react'
2+ // we'll use this to render our app to an html string
3+ import { renderToString } from 'react-dom/server'
4+ // and these to match the url to routes and then render
5+ import { match , RouterContext } from 'react-router'
6+ import routes from './modules/routes'
7+
8+ var express = require ( 'express' )
9+ var path = require ( 'path' )
10+ var compression = require ( 'compression' )
11+
12+ var app = express ( )
13+
14+ app . use ( compression ( ) )
15+ // serve static stuff
16+ app . use ( express . static ( path . join ( __dirname , 'public' ) ) )
17+
18+ //send all requests to index.html
19+ app . get ( '*' , ( req , res ) => {
20+
21+ match ( { routes : routes , location : req . url } , ( err , redirect , props ) => {
22+ match ( { routes : routes , location : req . url } , ( err , redirect , props ) => {
23+ // in here we can make some decisions all at once
24+ if ( err ) {
25+ // there was an error somewhere during route matching
26+ res . status ( 500 ) . send ( err . message )
27+ } else if ( redirect ) {
28+ // we haven't talked about `onEnter` hooks on routes, but before a
29+ // route is entered, it can redirect. Here we handle on the server.
30+ res . redirect ( redirect . pathname + redirect . search )
31+ } else if ( props ) {
32+ // if we got props then we matched a route and can render
33+ const appHtml = renderToString ( < RouterContext { ...props } /> )
34+ res . send ( renderPage ( appHtml ) )
35+ } else {
36+ // no errors, no redirect, we just didn't match anything
37+ res . status ( 404 ) . send ( 'Not Found' )
38+ }
39+ } )
40+ } )
41+
42+ } )
43+
44+ function renderPage ( appHtml ) {
45+ return `
46+ <!doctype html public="storage">
47+ <html>
48+ <meta charset=utf-8/>
49+ <title>My First React Router App</title>
50+ <link rel=stylesheet href=/index.css>
51+ <div id=app>${ appHtml } </div>
52+ <script src="/bundle.js"></script>
53+ `
54+ }
55+
56+ var PORT = process . env . PORT || 8080
57+ app . listen ( PORT , function ( ) {
58+
59+ console . log ( 'Production Express server running at localhost:' + PORT )
60+ } )
0 commit comments