-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
45 lines (41 loc) · 1.26 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
const express = require('express');
const server = express();
const fs = require('fs');
const path = require('path');
//obtain bundle
const bundle = require('./dist/server.bundle.js');
//get renderer from vue server renderer
const renderer = require('vue-server-renderer').createRenderer({
//set template
template: fs.readFileSync('./index.html', 'utf-8')
});
const port = 8080;
server.use('/dist', express.static(path.join(__dirname, './dist')));
//start server
server.get('*', (req, res) => {
bundle.default({ url: req.url }).then((app) => {
//context to use as data source
//in the template for interpolation
const context = {
title: 'Vue JS - Server Render',
meta: `
<meta description="vuejs server side render">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
`
};
renderer.renderToString(app, context, function (err, html) {
if (err) {
if (err.code === 404) {
res.status(404).end('Page not found')
} else {
res.status(500).end('Internal Server Error')
}
} else {
res.end(html)
}
});
}, (err) => {
console.log(err);
});
});
server.listen(port, () => console.log(`Server listening on port ${port}!`))