-
-
Notifications
You must be signed in to change notification settings - Fork 15.3k
/
server.js
89 lines (74 loc) · 2.32 KB
/
server.js
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
78
79
80
81
82
83
84
85
86
87
88
89
/* eslint-disable no-console, no-use-before-define */
import Express from 'express'
import qs from 'qs'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import webpackConfig from '../webpack.config'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import configureStore from '../common/store/configureStore'
import App from '../common/containers/App'
import { fetchCounter } from '../common/api/counter'
const app = new Express()
const port = 3000
// Use this middleware to set up hot module reloading via webpack.
const compiler = webpack(webpackConfig)
app.use(
webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: webpackConfig.output.publicPath
})
)
app.use(webpackHotMiddleware(compiler))
const handleRender = (req, res) => {
// Query our mock API asynchronously
fetchCounter(apiResult => {
// Read the counter from the request, if provided
const params = qs.parse(req.query)
const counter = parseInt(params.counter, 10) || apiResult || 0
// Compile an initial state
const preloadedState = { counter }
// Create a new Redux store instance
const store = configureStore(preloadedState)
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<App />
</Provider>
)
// Grab the initial state from our Redux store
const finalState = store.getState()
// Send the rendered page back to the client
res.send(renderFullPage(html, finalState))
})
}
// This is fired every time the server side receives a request
app.use(handleRender)
const renderFullPage = (html, preloadedState) => {
return `
<!doctype html>
<html>
<head>
<title>Redux Universal Example</title>
</head>
<body>
<div id="app">${html}</div>
<script>
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\x3c')}
</script>
<script src="/static/bundle.js"></script>
</body>
</html>
`
}
app.listen(port, error => {
if (error) {
console.error(error)
} else {
console.info(
`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`
)
}
})