-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.js
63 lines (52 loc) · 1.93 KB
/
server.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import express from 'express';
import React from 'react';
import Router from 'react-router';
import Helmet from 'react-helmet';
import routes from './routes';
/* create express server */
let app = express();
/* static files served from "public" through url /static/ */
app.use('/static', express.static('public'));
/* a single request handler receives every server request
and routes through react-router */
app.get('*', function(req, res) {
/* create a router and give it our routes
and the requested path */
let router = Router.create({
location: req.url,
routes: routes,
});
router.run(function(Root, state) {
/* render `Root` (the complete document) to string
and rewind Helmet for access to its data.
Read about why rewinding is necessary on the server:
https://github.com/nfl/react-helmet#server-usage */
let renderedBody = React.renderToString(<Root />);
let head = Helmet.rewind();
/* render document with Helmet-rendered `<head>` info
and React-rendered body. then, initialize the client
side via `client.js`.
Note: Helmet will update your page's `<head`> on the client
side, but you must construct `<head>` manually
on the server. */
let html = `
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>${head.title}</title>
${head.meta}
${head.link}
</head>
<body>
<div id="app">${renderedBody}</div>
<script src="/static/client.js"></script>
</body>
</html>
`;
/* write html, close connection */
res.write(html);
res.end();
});
});
app.listen(8080, () => console.log('Listening on http://localhost:8080'));