|
1 | 1 | /**
|
2 | 2 | * Created by heoo442 on 2016/6/5.
|
3 | 3 | */
|
4 |
| -var express = require('express') |
5 |
| -var path = require('path') |
6 |
| -var compression = require('compression') |
| 4 | +import express from 'express' |
| 5 | +import path from 'path' |
| 6 | +import compression from 'compression' |
| 7 | +import React from 'react'; |
| 8 | +import {renderToString} from 'react-dom/server'; |
| 9 | +import {match,RouterContext} from 'react-router'; |
| 10 | +import routes from './modules/routes'; |
7 | 11 |
|
8 | 12 | var app = express()
|
9 |
| -//must be first |
10 |
| -app.use(compression()) |
11 |
| -app.use(express.static(path.join(path.resolve(__dirname), 'public'))) |
| 13 | +app.use(compression()); ////must be first |
| 14 | +app.use(express.static(path.join(path.resolve(__dirname), 'public'), {index: false})); |
12 | 15 |
|
13 |
| -app.get('*', function (req, res) { |
14 |
| - res.sendFile(path.join(path.resolve(__dirname), 'public', 'index.html')) |
15 |
| -}) |
| 16 | +app.get('*', (req, res) => { |
| 17 | + match({routes: routes, location: req.url}, (err, redirect, props)=> { |
| 18 | + if (err) { |
| 19 | + res.status(500).send(err.message); |
| 20 | + } else if (redirect) { |
| 21 | + res.redirect(redirect.pathname + redirect.search); |
| 22 | + } else if (props) { |
| 23 | + const appHtml = renderToString(<RouterContext {...props}/>); |
| 24 | + res.send(renderPage(appHtml)); |
| 25 | + } else { |
| 26 | + res.status(404).send('Not Found'); |
| 27 | + } |
| 28 | + }); |
| 29 | +}); |
| 30 | + |
| 31 | +function renderPage(appHtml) { |
| 32 | + return ` |
| 33 | + <!doctype html public="storage"> |
| 34 | + <html> |
| 35 | + <meta charset=utf-8/> |
| 36 | + <title>My First React Router App</title> |
| 37 | + <link rel="stylesheet" href=/index.css> |
| 38 | + <div id=app>${appHtml}</div> |
| 39 | + <script src="/bundle.js"></script> |
| 40 | + `; |
| 41 | +} |
16 | 42 |
|
17 |
| -var PORT = process.env.PORT || 8080 |
| 43 | +var PORT = process.env.PORT || 8088 |
18 | 44 | app.listen(PORT, function () {
|
19 | 45 | console.log('Production Express server running at localhost:' + PORT)
|
20 | 46 | })
|
|
0 commit comments