-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
68 lines (54 loc) · 1.56 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
const express = require('express');
const path = require('path');
const fs = require('fs');
const serialize = require('serialize-javascript');
const { createBundleRenderer } = require('vue-server-renderer');
const config = {
port: process.env.PORT || 3000
};
const app = express();
const indexHTML = fs.readFileSync(
path.join(__dirname, 'public', 'index.html'),
'utf-8'
);
const appBundle = fs.readFileSync(
path.join(__dirname, 'ssr', 'App.js'),
'utf-8'
);
app.use(express.static('public'));
if (process.env.NODE_ENV === 'development') {
// require('./build/dev-server')(app);
console.info(`Running on ${process.env.NODE_ENV} mode`);
}
app.get('/*', (req, res) => {
const renderer = createBundleRenderer(appBundle);
const context = { url: req.url };
renderer.renderToString(context, (err, html) => {
if (err) {
console.log(err);
return res.status(500).send('server error');
}
let ssrIndexHTML = indexHTML.replace('{{APP}}', html);
ssrIndexHTML = ssrIndexHTML.replace(
'{{STATE}}',
`<script type="text/javascript">window.__INITIAL_STATE__=${serialize(
context.state,
{
isJSON: true
}
)}</script>`
);
res.write(ssrIndexHTML);
res.end();
});
});
app.use((req, res, next) => {
res.status(404).send('Sorry cant find that!<br><a href="/">go back</a>');
});
app.listen(config.port, () => {
const runAdrres =
process.env.NODE_ENV === 'development'
? `http://localhost:${config.port}`
: `port ${config.port}...`;
console.info(`Running on ${runAdrres}`);
});