Files: b9e6e111da28035dc87670c94c75996c4b6854f5 / app / stack / render.js
1990 bytesRaw
1 | // https://github.com/jlongster/react-redux-universal-hot-example/blob/master/src/server.js |
2 | |
3 | const React = require('react') |
4 | const { renderToString } = require('react-dom/server') |
5 | const { Provider } = require('react-redux') |
6 | const { createHistory } = require('history') |
7 | const { Router, RoutingContext, match } = require('react-router') |
8 | |
9 | const createStore = require('app/store') |
10 | const routes = require('app/routes') |
11 | const fetchAllData = require('app/util/fetch-all-data') |
12 | |
13 | module.exports = createRender |
14 | |
15 | function createRender (config) { |
16 | return function render (req, res) { |
17 | const store = createStore() |
18 | |
19 | match({ |
20 | routes: routes, |
21 | location: req.path |
22 | }, function (err, redirectLocation, renderProps) { |
23 | if (redirectLocation) { |
24 | res.redirect(redirectLocation.pathname + redirectLocation.search) |
25 | } else if (err) { |
26 | res.status(500).send(err.message) |
27 | } else if (!renderProps) { |
28 | res.status(404).send('Not found') |
29 | } else { |
30 | fetchAllData( |
31 | renderProps.components, |
32 | store.getState, store.dispatch, |
33 | renderProps.location, |
34 | renderProps.params |
35 | ).then(function () { |
36 | const component = <Provider store={store} key="provider"> |
37 | <RoutingContext { ...renderProps } /> |
38 | </Provider> |
39 | |
40 | const innerHtml = renderToString(component) |
41 | |
42 | const html = renderFullPage(innerHtml, store.getState()) |
43 | |
44 | res.send(html) |
45 | }) |
46 | } |
47 | }) |
48 | } |
49 | } |
50 | |
51 | function renderFullPage (innerHtml, initialData) { |
52 | return ` |
53 | <!DOCTYPE html> |
54 | <html lang="en"> |
55 | <head> |
56 | <meta charset="utf-8" /> |
57 | <title>Craftworks TodoMVC</title> |
58 | <meta name="viewport" content="width=device-width, initial-scale=1" /> |
59 | </head> |
60 | <body> |
61 | <main>${ innerHtml }</main> |
62 | <script> |
63 | window.__data = ${ JSON.stringify(initialData) } |
64 | </script> |
65 | <script src="bundle.js"></script> |
66 | </body> |
67 | </html> |
68 | ` |
69 | } |
70 |
Built with git-ssb-web