|
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' |
4 | 8 |
|
5 | 9 | var app = express()
|
6 | 10 |
|
7 | 11 | app.use(compression())
|
8 | 12 |
|
9 | 13 | // serve our static stuff like index.css
|
10 |
| -app.use(express.static(path.join(__dirname, 'public'))) |
| 14 | +app.use(express.static(path.join(__dirname, 'public'), {index: false})) |
11 | 15 |
|
12 |
| -app.get('*', function(req, res) { |
13 |
| - res.sendFile(path.join(__dirname, 'public', 'index.html')) |
| 16 | +// send all requests to index.html so browserHistory works |
| 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 | + }) |
14 | 31 | })
|
15 | 32 |
|
16 |
| -var PORT = process.env.PORT || 8080 |
| 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 | +} |
17 | 44 |
|
18 |
| -app.listen(PORT, function(){ |
19 |
| - console.log('Production Express server running at localhost:' + PORT) |
| 45 | +var PORT = process.env.PORT || 8080 |
| 46 | +app.listen(PORT, function() { |
| 47 | + console.log('Production Express server running at localhost:' + PORT) |
20 | 48 | })
|
0 commit comments