forked from reactjs/react-router-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
44 lines (36 loc) · 1.12 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
require('babel-register')({
only: /\/react-top-to-bottom\/(server.jsx|modules\/)/,
presets: ['es2015', 'react'],
extensions: ['.jsx', '.js'],
});
const express = require('express');
const path = require('path');
const compression = require('compression');
const ReactDOMServer = require('react-dom/server');
const appToRender = require('./server.jsx');
const app = express();
app.use(compression());
// serve our static stuff like index.css
app.use(express.static(path.join(__dirname, 'public'), { index: false }));
const PROPS = { answer: 42 };
// send all requests to index.html so browserHistory works
app.get('*', (req, res) => {
const context = {};
const html = ReactDOMServer.renderToString(
appToRender(req.url, context, PROPS)
);
// context.url will contain the URL to redirect to if a <Redirect> was used
if (context.url) {
res.writeHead(
302,
{ Location: context.url }
);
res.end();
} else {
res.send(`<!doctype html>${html}`);
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Production Express server running at localhost:${PORT}`);
});