72 lines
2.4 KiB
JavaScript
72 lines
2.4 KiB
JavaScript
|
|
const http = require("http");
|
||
|
|
const https = require("https");
|
||
|
|
const fs = require("fs");
|
||
|
|
const path = require("path");
|
||
|
|
|
||
|
|
const port = Number(process.env.PORT) || 18080;
|
||
|
|
const root = __dirname;
|
||
|
|
const apiOrigin = "https://qhse.cncecoa.com";
|
||
|
|
const mimeTypes = {
|
||
|
|
".html": "text/html; charset=utf-8",
|
||
|
|
".css": "text/css; charset=utf-8",
|
||
|
|
".js": "application/javascript; charset=utf-8",
|
||
|
|
".json": "application/json; charset=utf-8",
|
||
|
|
".pdf": "application/pdf",
|
||
|
|
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||
|
|
};
|
||
|
|
|
||
|
|
function proxyApi(request, response) {
|
||
|
|
const target = new URL(request.url, apiOrigin);
|
||
|
|
const headers = { ...request.headers, host: target.host };
|
||
|
|
delete headers.origin;
|
||
|
|
delete headers.referer;
|
||
|
|
|
||
|
|
const proxyRequest = https.request(target, {
|
||
|
|
method: request.method,
|
||
|
|
headers
|
||
|
|
}, (proxyResponse) => {
|
||
|
|
response.writeHead(proxyResponse.statusCode || 502, proxyResponse.headers);
|
||
|
|
proxyResponse.pipe(response);
|
||
|
|
});
|
||
|
|
|
||
|
|
proxyRequest.on("error", (error) => {
|
||
|
|
response.writeHead(502, { "Content-Type": "application/json; charset=utf-8" });
|
||
|
|
response.end(JSON.stringify({ code: 0, message: `接口代理失败:${error.message}`, data: null }));
|
||
|
|
});
|
||
|
|
request.pipe(proxyRequest);
|
||
|
|
}
|
||
|
|
|
||
|
|
function serveStatic(request, response) {
|
||
|
|
const requestPath = decodeURIComponent(new URL(request.url, "http://localhost").pathname);
|
||
|
|
const relativePath = requestPath === "/" ? "indexV2.html" : requestPath.replace(/^\/+/, "");
|
||
|
|
const filePath = path.resolve(root, relativePath);
|
||
|
|
if (filePath !== root && !filePath.startsWith(`${root}${path.sep}`)) {
|
||
|
|
response.writeHead(403);
|
||
|
|
response.end("Forbidden");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
fs.stat(filePath, (statError, stat) => {
|
||
|
|
if (statError || !stat.isFile()) {
|
||
|
|
response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
||
|
|
response.end("Not Found");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
response.writeHead(200, {
|
||
|
|
"Content-Type": mimeTypes[path.extname(filePath).toLowerCase()] || "application/octet-stream",
|
||
|
|
"Cache-Control": "no-cache"
|
||
|
|
});
|
||
|
|
fs.createReadStream(filePath).pipe(response);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
http.createServer((request, response) => {
|
||
|
|
if (request.url.startsWith("/qhse_webapi/")) {
|
||
|
|
proxyApi(request, response);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
serveStatic(request, response);
|
||
|
|
}).listen(port, "127.0.0.1", () => {
|
||
|
|
console.log(`数据治理看板:http://127.0.0.1:${port}/indexV2.html`);
|
||
|
|
});
|