-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhost_client_app.js
More file actions
75 lines (62 loc) · 2.23 KB
/
host_client_app.js
File metadata and controls
75 lines (62 loc) · 2.23 KB
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
const express = require('express');
const createProxyMiddleware = require('http-proxy-middleware').createProxyMiddleware;
const fs = require('fs');
const path = require('path');
const app = express();
const options = {
target: 'localhost:8080', // target host
port: 80,
dist: '/opt/homium/client-app/dist'
};
// parse parameters
process.argv.forEach((val, index) => {
if (val === '--target') {
options.target = process.argv[index + 1];
}
if (val === '--port') {
options.port = parseInt(process.argv[index + 1]);
}
if (val === '--dist') {
options.dist = process.argv[index + 1];
}
});
// proxy /api to options.target + '/api'
app.use(createProxyMiddleware('/api', {
target: `http://${options.target}`, changeOrigin: true, onProxyReq: (proxyReq, req, res) => {
proxyReq.setHeader('Host', req.headers.host);
}
}));
let apiWsProxy = createProxyMiddleware('/api', { target: `ws://${options.target}`, ws: true, changeOrigin: true });
app.use(createProxyMiddleware('/extensions', {
target: `http://${options.target}`, changeOrigin: true, onProxyReq: (proxyReq, req, res) => {
proxyReq.setHeader('Host', req.headers.host);
}
}));
let extensionWsProxy = createProxyMiddleware('/extensions', { target: `ws://${options.target}`, ws: true, changeOrigin: true });
app.use(createProxyMiddleware('/extension-info', {
target: `http://${options.target}`, changeOrigin: true, onProxyReq: (proxyReq, req, res) => {
proxyReq.setHeader('Host', req.headers.host);
}
}));
// add use for static files
app.use(express.static(options.dist));
// add use for SPA
app.use((req, res) => {
if (fs.existsSync(path.join(options.dist, req.url))) {
res.sendFile(path.join(options.dist, req.url));
} else {
res.sendFile(path.join(options.dist, 'index.html'));
}
});
let server = app.listen(options.port, () => {
console.log(`App listening at http://127.0.0.1:${options.port}`);
});
server.on('upgrade', (req, socket, head) => {
if (req.url.startsWith('/api')) {
apiWsProxy.upgrade(req, socket, head);
} else if (req.url.startsWith('/extensions')) {
extensionWsProxy.upgrade(req, socket, head);
} else {
socket.destroy();
}
});