-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.jsx
52 lines (50 loc) · 1.88 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
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 { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import reducer from 'reducers';
import Immutable from 'immutable';
const app = express();
app.use(express.static('public'))
app.use((req, res) => {
const store = createStore(reducer);
const location = createLocation(req.url);
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.');
const InitialComponent = (
<Provider store = {store}>
<RoutingContext {...renderProps} />
</Provider>
);
const initialState = store.getState();
const componentHTML = renderToString(InitialComponent);
const HTML = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Shopping Cart</title>
<script type="application/javascript">
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
</script>
<link href="/css/styles.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div id="react-view">${componentHTML}</div>
<script type="application/javascript" src="/bundle.js"></script>
</body>
</html>
`
res.end(HTML);
});
});
export default app;