Files: d393015f835e882e9ded1efb5f5b459f624ee943 / app / stack / render.js
2164 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 | var innerHtml |
41 | try { |
42 | innerHtml = renderToString(component) |
43 | } catch (err) { |
44 | res.setHeader('content-type', 'text/plain') |
45 | res.status(500).send(err.stack) |
46 | } |
47 | |
48 | const html = renderFullPage(innerHtml, store.getState()) |
49 | |
50 | res.send(html) |
51 | }) |
52 | } |
53 | }) |
54 | } |
55 | } |
56 | |
57 | function renderFullPage (innerHtml, initialData) { |
58 | return ` |
59 | <!DOCTYPE html> |
60 | <html lang="en"> |
61 | <head> |
62 | <meta charset="utf-8" /> |
63 | <title>Craftworks TodoMVC</title> |
64 | <meta name="viewport" content="width=device-width, initial-scale=1" /> |
65 | </head> |
66 | <body> |
67 | <main>${ innerHtml }</main> |
68 | <script> |
69 | window.__data = ${ JSON.stringify(initialData) } |
70 | </script> |
71 | <script src="bundle.js"></script> |
72 | </body> |
73 | </html> |
74 | ` |
75 | } |
76 |
Built with git-ssb-web