forked from michaelcheng924/react-redux-fullstack-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.jsx
70 lines (58 loc) · 2.05 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
import express from 'express';
import bodyParser from 'body-parser';
import path from 'path';
import React from 'react';
import {Provider} from 'react-redux';
import routes from 'routes';
import createLocation from 'history/lib/createLocation';
import {renderToString} from 'react-dom/server';
import {RoutingContext, match} from 'react-router';
import serverRoutes from './app/server/routes';
import {makeStore} from './app/helpers';
import {setItems, setCart} from './app/actions/ProductsActions';
import items from './app/server/fake-database-items.js';
import cart from './app/server/fake-database-cart.js';
const app = express();
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
serverRoutes(app);
app.use((req, res) => {
const location = createLocation(req.url);
const store = makeStore();
match({routes, location}, (err, redirectLocation, renderProps) => {
if (err) {
console.log(err);
return res.status(500).end('Internal server error');
}
if (!renderProps) {
return res.status(404).end('Not found.');
}
const InitialComponent = (
<Provider store={store}>
<RoutingContext {...renderProps} />
</Provider>
);
store.dispatch(setItems(items));
store.dispatch(setCart(cart));
const initialState = store.getState();
const componentHTML = renderToString(InitialComponent);
const HTML = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React Redux Fullstack Starter</title>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
</script>
</head>
<body>
<div id="app">${componentHTML}</div>
<script src="/bundle.js"></script>
</body>
</html>
`;
res.end(HTML);
});
});
module.exports = app;