forked from bananaoomarang/isomorphic-redux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.jsx
77 lines (63 loc) · 2.21 KB
/
server.jsx
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server'
import { RoutingContext, match } from 'react-router';
import createLocation from 'history/lib/createLocation';
import routes from 'routes';
import { Provider } from 'react-redux';
import * as reducers from 'reducers';
import promiseMiddleware from 'lib/promiseMiddleware';
import fetchComponentData from 'lib/fetchComponentData';
import { createStore,
combineReducers,
applyMiddleware } from 'redux';
import path from 'path';
const app = express();
if (process.env.NODE_ENV !== 'production') {
require('./webpack.dev').default(app);
}
app.use(express.static(path.join(__dirname, 'dist')));
app.use( (req, res) => {
const location = createLocation(req.url);
const reducer = combineReducers(reducers);
const store = applyMiddleware(promiseMiddleware)(createStore)(reducer);
match({ routes, location }, (err, redirectLocation, renderProps) => {
if(err) {
console.error(err);
return res.status(500).end('Internal server error');
}
if(!renderProps)
return res.status(404).end('Not found');
function renderView() {
const InitialView = (
<Provider store={store}>
<RoutingContext {...renderProps} />
</Provider>
);
const componentHTML = renderToString(InitialView);
const initialState = store.getState();
const HTML = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Redux Demo</title>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
</script>
</head>
<body>
<div id="react-view">${componentHTML}</div>
<script type="application/javascript" src="/bundle.js"></script>
</body>
</html>
`;
return HTML;
}
fetchComponentData(store.dispatch, renderProps.components, renderProps.params)
.then(renderView)
.then(html => res.end(html))
.catch(err => res.end(err.message));
});
});
export default app;