-
Notifications
You must be signed in to change notification settings - Fork 27
/
server.js
90 lines (77 loc) · 2.17 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
90
const fs = require("fs");
const path = require("path");
const express = require("express");
var proxy = require("http-proxy-middleware");
const { createBundleRenderer } = require("vue-server-renderer");
const devServerBaseURL = process.env.DEV_SERVER_BASE_URL || "http://localhost";
const devServerPort = process.env.DEV_SERVER_PORT || 8080;
const app = express();
function createRenderer(bundle, options) {
return createBundleRenderer(
bundle,
Object.assign(options, {
runInNewContext: false
})
);
}
let renderer;
const templatePath = path.resolve(__dirname, "./src/index.template.html");
const bundle = require("./dist/vue-ssr-server-bundle.json");
const template = fs.readFileSync(templatePath, "utf-8");
const clientManifest = require("./dist/vue-ssr-client-manifest.json");
renderer = createRenderer(bundle, {
template,
clientManifest
});
if (process.env.NODE_ENV !== "production") {
app.use(
"/js/main*",
proxy({
target: `${devServerBaseURL}/${devServerPort}`,
changeOrigin: true,
pathRewrite: function(path) {
return path.includes("main") ? "/main.js" : path;
},
prependPath: false
})
);
app.use(
"/*hot-update*",
proxy({
target: `${devServerBaseURL}/${devServerPort}`,
changeOrigin: true
})
);
app.use(
"/sockjs-node",
proxy({
target: `${devServerBaseURL}/${devServerPort}`,
changeOrigin: true,
ws: true
})
);
}
app.use("/js", express.static(path.resolve(__dirname, "./dist/js")));
app.use("/css", express.static(path.resolve(__dirname, "./dist/css")));
app.get("*", (req, res) => {
res.setHeader("Content-Type", "text/html");
const context = {
title: "WordExpress Starter Vue", // default title
url: req.url
};
renderer.renderToString(context, (err, html) => {
if (err) {
if (err.url) {
res.redirect(err.url);
} else {
// Render Error Page or Redirect
res.status(500).end("500 | Internal Server Error");
console.error(`error during render : ${req.url}`);
console.error(err.stack);
}
}
res.status(context.HTTPStatus || 200);
res.send(html);
});
});
module.exports = app;