-
Notifications
You must be signed in to change notification settings - Fork 609
/
vite.proxy.js
45 lines (40 loc) · 1.11 KB
/
vite.proxy.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 http = require('http');
const httpProxy = require('http-proxy');
const app = express();
const fromPort = 80;
const toPort = 8080;
const host = 'localhost';
app.set('etag', false);
app.use((req, res, next) => {
res.set('Cache-Control', 'no-store');
next();
});
app.get('*', async(req, res) => {
const promise = fetch(`http://${host}:${toPort}` + req.url);
const fetchResponse = await promise;
fetchResponse.headers.forEach((value, key) => {
res.setHeader(key, value);
});
const clone = fetchResponse.clone();
let text = await fetchResponse.text();
if(text.includes(`${host}:${toPort}`)) {
text = text.replace(`${host}:${toPort}`, `${host}:${fromPort}`);
res.send(text);
} else {
const arrayBuffer = await clone.arrayBuffer();
const array = new Uint8Array(arrayBuffer);
res.write(array);
res.end();
}
});
const server = http.createServer(app).listen(fromPort);
server.on('upgrade', (req, socket, head) => {
proxy.ws(req, socket, head);
});
const proxy = new httpProxy.createProxyServer({
target: {
host: host,
port: toPort
}
});