Files: 2feb98c1e6e7d51eb76ec441dc2a134829471edd / app / render.js
2489 bytesRaw
1 | // https://github.com/jlongster/react-redux-universal-hot-example/blob/master/src/server.js |
2 | |
3 | import http from 'http' |
4 | import Url from 'url' |
5 | import React from 'react' |
6 | import { renderToString } from 'react-dom/server' |
7 | import { Provider } from 'react-redux' |
8 | import { createHistory } from 'history' |
9 | import { Router, RoutingContext, match } from 'react-router' |
10 | import sendHtml from 'send-data/html' |
11 | import sendError from 'send-data/error' |
12 | import redirect from 'predirect' |
13 | |
14 | import createStore from 'app/store' |
15 | import routes from 'app/routes' |
16 | import fetchAllData from 'app/util/fetch-all-data' |
17 | |
18 | export default module.exports = createRender |
19 | |
20 | function createRender (config) { |
21 | const staticUrl = Url.format(config.static.url) |
22 | |
23 | return http.createServer(render) |
24 | |
25 | function render (req, res) { |
26 | const store = createStore() |
27 | |
28 | match({ |
29 | routes: routes, |
30 | location: req.url |
31 | }, function (err, redirectLocation, renderProps) { |
32 | if (redirectLocation) { |
33 | redirect(req, res, redirectLocation.pathname + redirectLocation.search) |
34 | } else if (err) { |
35 | sendError(req, res, { body: err }) |
36 | } else if (!renderProps) { |
37 | sendError(req, res, { |
38 | statusCode: 404, |
39 | body: new Error('Not found') |
40 | }) |
41 | } else { |
42 | fetchAllData( |
43 | renderProps.components, |
44 | store.getState, store.dispatch, |
45 | renderProps.location, |
46 | renderProps.params |
47 | ).then(function () { |
48 | const component = <Provider store={store} key="provider"> |
49 | <RoutingContext { ...renderProps } /> |
50 | </Provider> |
51 | |
52 | var innerHtml |
53 | try { |
54 | innerHtml = renderToString(component) |
55 | } catch (err) { |
56 | return sendError(req, res, { body: err }) |
57 | } |
58 | |
59 | const html = renderFullPage(innerHtml, store.getState(), config) |
60 | |
61 | sendHtml(req, res, html) |
62 | }) |
63 | } |
64 | }) |
65 | } |
66 | |
67 | function renderFullPage (innerHtml, initialData) { |
68 | return ` |
69 | <!DOCTYPE html> |
70 | <html lang="en"> |
71 | <head> |
72 | <meta charset="utf-8" /> |
73 | <title>Craftworks TodoMVC</title> |
74 | <meta name="viewport" content="width=device-width, initial-scale=1" /> |
75 | </head> |
76 | <body> |
77 | <main>${ innerHtml }</main> |
78 | <script> |
79 | window.__data = ${ JSON.stringify(initialData) } |
80 | </script> |
81 | <script src="${Url.resolve(staticUrl, 'bundle.js')}"></script> |
82 | </body> |
83 | </html> |
84 | ` |
85 | } |
86 | } |
87 | |
88 |
Built with git-ssb-web