提交 5c5eaf24 authored 作者: 汪雄's avatar 汪雄

全部提交

上级 674e82f2
File added
......@@ -10,7 +10,7 @@
"dependencies": {
"ant-design-vue": "^4.2.6",
"axios": "0.28.1",
"dayjs": "^1.11.19",
"dayjs": "^1.11.20",
"echarts": "5.5.1",
"element-plus": "^2.9.6",
"express": "^5.1.0",
......@@ -3215,10 +3215,9 @@
}
},
"node_modules/dayjs": {
"version": "1.11.19",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.19.tgz",
"integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==",
"license": "MIT"
"version": "1.11.20",
"resolved": "https://registry.npmmirror.com/dayjs/-/dayjs-1.11.20.tgz",
"integrity": "sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ=="
},
"node_modules/debug": {
"version": "4.4.3",
......
......@@ -24,7 +24,7 @@
"dependencies": {
"ant-design-vue": "^4.2.6",
"axios": "0.28.1",
"dayjs": "^1.11.19",
"dayjs": "^1.11.20",
"echarts": "5.5.1",
"element-plus": "^2.9.6",
"express": "^5.1.0",
......
const express = require('express');
const path = require('path');
const http = require('http');
const WebSocket = require('ws');
const { createProxyMiddleware } = require('http-proxy-middleware');
const fs = require('fs');
const express = require("express");
const path = require("path");
const http = require("http");
const WebSocket = require("ws");
const { createProxyMiddleware } = require("http-proxy-middleware");
const fs = require("fs");
const app = express();
const PORT = 3010;
// 检测是否在 pkg 打包环境中
const isPacked = typeof process.pkg !== 'undefined';
const isPacked = typeof process.pkg !== "undefined";
// 动态获取静态文件路径
function getStaticPath() {
if (isPacked) {
const possiblePaths = [
path.join(process.cwd(), 'dist'),
path.join(__dirname, 'dist')
path.join(process.cwd(), "dist"),
path.join(__dirname, "dist"),
];
for (const staticPath of possiblePaths) {
try {
const testPath = path.join(staticPath, 'index.html');
const testPath = path.join(staticPath, "index.html");
if (fs.existsSync(testPath)) {
//console.log(`Found static files at: ${staticPath}`);
return staticPath;
......@@ -29,9 +29,9 @@ function getStaticPath() {
continue;
}
}
return path.join(__dirname, 'dist');
return path.join(__dirname, "dist");
} else {
return path.join(__dirname, 'dist');
return path.join(__dirname, "dist");
}
}
......@@ -40,68 +40,99 @@ console.log(`Serving static files from: ${staticPath}`);
// 1. CORS 中间件 - 放在最前面
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-API-Key');
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, PATCH",
);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization, X-API-Key",
);
// 处理预检请求
if (req.method === 'OPTIONS') {
if (req.method === "OPTIONS") {
return res.status(200).end();
}
next();
});
// app.use((req, res, next) => {
// console.log('👉 请求进来了:', req.url);
// next();
// });
// 2. CSP配置 - 简化版本避免冲突
app.use((req, res, next) => {
// 对于API请求,使用更宽松的CSP或者不设置
if (req.path.startsWith('/api')) {
if (req.path.startsWith("/api")) {
next();
} else {
res.setHeader('Content-Security-Policy',
res.setHeader(
"Content-Security-Policy",
"default-src 'self' 'unsafe-inline' 'unsafe-eval'; " +
"connect-src 'self' http: https: ws: wss:; " +
"img-src 'self' data: blob: http: https:;"
"connect-src 'self' http: https: ws: wss:; " +
"img-src 'self' data: blob: http: https:;",
);
next();
}
});
// 3. API代理 - 简化版本
app.use('/api', createProxyMiddleware({
target: 'http://127.0.0.1:19020', // 后端API地址
// target: 'http://121.229.107.155:2251',
// target: 'http://121.229.107.155:2251',//测试环境
target: 'http://121.229.107.155:19021',//生产环境
// target: 'http://127.0.0.1:19021',//生产环境
changeOrigin: true,
pathRewrite: { '^/api': '/api' },
logLevel: 'debug',
// pathRewrite: { '^/api1': '/api' }, //进来的path没有api了,要么直接用app.use((req, res, next)=>{})
pathRewrite: function (path, req) {
// console.log('31800是否走了代理', path);
//由于app.use('/api')的原因,进入到这里后path是被去掉了api,所以要重新加上,
return '/api' + path;
},
logLevel: 'silent',
// 调试代理请求
onProxyReq: function (proxyReq, req, res) {
// 手动设置正确的路径(如果必要)
// const originalPath = req.originalUrl;
// if (originalPath.startsWith('/api1')) {
// const newPath = originalPath.replace('/api1', '/api');
// console.log('手动重写路径:', originalPath, '->', newPath);
// proxyReq.path = newPath;
// }
},
onProxyRes: function (proxyRes, req, res) {
// 确保代理响应包含正确的CORS头
proxyRes.headers['Access-Control-Allow-Origin'] = '*';
// 确保 CORS 头存在
const origin = req.headers.origin;
// 设置响应头
if (origin && ['http://localhost:3010', 'http://127.0.0.1:3010'].includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
} else {
res.setHeader('Access-Control-Allow-Origin', '*');
}
proxyRes.headers['Access-Control-Allow-Credentials'] = 'true';
},
onError: (err, req, res) => {
console.error('Proxy Error:', err);
res.status(500).json({ error: 'Proxy error' });
},
// ws: true, // ws 转发
}
}));
// 4. 静态文件服务
app.use(express.static(staticPath));
// 5. 处理根路径请求
app.get('/', (req, res) => {
const indexPath = path.join(staticPath, 'index.html');
app.get("/", (req, res) => {
const indexPath = path.join(staticPath, "index.html");
if (fs.existsSync && !fs.existsSync(indexPath)) {
console.error(`Index.html not found at: ${indexPath}`);
return res.status(404).send('index.html not found');
return res.status(404).send("index.html not found");
}
res.sendFile(indexPath);
});
// 6. 处理.well-known路径
app.get('/.well-known/appspecific/com.chrome.devtools.json', (req, res) => {
// 6. 处理.well-known路径
app.get("/.well-known/appspecific/com.chrome.devtools.json", (req, res) => {
res.json({});
});
......@@ -111,27 +142,24 @@ const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
wss.on("connection", (ws) => {
//console.log(ws, '连接------');
ws.send('连接成功');
ws.on('message', (message) => {
ws.send("连接成功");
ws.on("message", (message) => {
//console.log(message.toString(), ':ue发送给vue的数据');
ws.send('vue发给ue的数据+1');
ws.send("vue发给ue的数据+1");
});
ws.on('close', () => {
ws.on("close", () => {
//console.log('客户端断开连接');
});
ws.on('error', (error) => {
console.error('WebSocket错误:', error);
ws.on("error", (error) => {
console.error("WebSocket错误:", error);
});
});
server.listen(PORT, () => {
//console.log(`大屏中转服务启动: http://localhost:${PORT}`);
//console.log(`静态文件目录: ${staticPath}`);
//console.log(`运行模式: ${isPacked ? '打包模式' : '开发模式'}`);
// console.log(`大屏中转服务启动: http://localhost:${PORT}`);
// console.log(`静态文件目录: ${staticPath}`);
// console.log(`运行模式: ${isPacked ? "打包模式" : "开发模式"}`);
});
This source diff could not be displayed because it is too large. You can view the blob instead.
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论