liufumingren bd2363bf00 chore: 初始化仓库(backend / frontend / extension 三块)
- backend/:Egg 3 纯 JSON 接口服务(MySQL 8 + Redis),全部走 header 令牌鉴权;
  已彻底去掉服务端渲染(删除 page 控制器 / app/view / nunjucks / session / CSRF),
  开发时把页面请求反代到前端 dev server,生产托管 frontend/dist(SPA 回退)。
  单测 91 个通过(不需要本机数据库)。
- frontend/:Vite + Vue3 + TypeScript 的 SPA(登录 / 注册 / 找回密码 / 扫码登录与确认 /
  首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页),vue-tsc 类型检查与构建通过。
- extension/:MV3 浏览器扩展(零构建),注入第三方 WMS 页面识别运单号并打开溯源页。
- 忽略规则统一放根 .gitignore:node_modules、dist、logs / logs-*、run、typings、
  .env*、config.local.js(含本机数据库与 Redis 密码,绝不入库)。
2026-10-17 08:50:32 +08:00

109 lines
4.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const fs = require('fs');
const path = require('path');
const httpProxy = require('http-proxy');
const serve = require('koa-static');
/**
* 前端入口:**后端不再渲染任何页面**,`/` 这一侧要么反代给前端 dev server、要么托管前端构建产物
*
* - **开发(`env=local`)**:把非 `/api`、`/health` 的请求反向代理到前端 dev server
* (`config.frontend.devServer`,默认 `http://127.0.0.1:7301`,即 `frontend && npm run dev`)。
* 这样联调只开一个地址(后端 `:7001`),前端的热更新也照常生效(含 HMR 的 WebSocket 升级)。
* - **生产**:托管 `config.frontend.distDir`(默认 `../frontend/dist`)里的静态资源,
* 找不到文件且浏览器要 HTML 时回退到 `index.html`(SPA 深链刷新不会 404)。
* - **单测(`env=unittest`)**:整体跳过(不连前端、也不要求 dist 存在),
* 于是未匹配的路径还是走框架/路由自己的 404。
*
* 只接管 GET/HEAD 的「非接口」请求:`/api/*`、`/health` 一律交给后面的路由。
*/
module.exports = (options, app) => {
const cfg = app.config.frontend || {};
const env = app.config.env;
const isDev = env === 'local';
const enabled = Boolean(cfg.enable) && env !== 'unittest';
const distDir = cfg.distDir;
const indexFile = path.join(distDir, 'index.html');
// 静态中间件(生产用):只管真实文件,交给 koa-static 处理缓存/条件请求
const staticMw = enabled && !isDev ? serve(distDir, { index: false, defer: false }) : null;
if (enabled && isDev) {
app.logger.info('[frontend] dev 反代已启用: %s(页面请求转发给前端 dev server)', cfg.devServer);
// 前端 dev server 的 HMR 走 WebSocket:HTTP server 的 upgrade 事件也得转过去,
// 否则页面能打开、但改代码不会热更新(升级请求没人管会直接断开)
app.once('server', server => {
server.on('upgrade', (req, socket, head) => {
const url = String(req.url || '');
if (url.startsWith('/api/') || url === '/health') return; // 接口侧不接管
getProxy(cfg.devServer).ws(req, socket, head, { target: cfg.devServer });
});
});
} else if (enabled && staticMw) {
app.logger.info('[frontend] 静态托管已启用: %s(存在 index.html = %s)', distDir, fs.existsSync(indexFile));
}
return async function frontend(ctx, next) {
if (!enabled || !isFrontendRequest(ctx)) return next();
if (isDev) return proxyToDevServer(ctx, cfg.devServer);
// 生产:先当静态资源找,找不到再回退 index.html(SPA 路由)
await staticMw(ctx, async () => {});
if (ctx.status !== 404) return;
if (!fs.existsSync(indexFile)) {
ctx.status = 503;
ctx.type = 'html';
ctx.body = '<h1>前端还没构建</h1><p>请在 frontend/ 执行 <code>npm run build</code>(或用 FRONTEND_DIST 指定目录)。</p>';
return;
}
ctx.type = 'html';
ctx.body = fs.createReadStream(indexFile);
};
};
/** 只接管「页面」请求:非接口 + GET/HEAD */
function isFrontendRequest(ctx) {
if (ctx.method !== 'GET' && ctx.method !== 'HEAD') return false;
return !ctx.path.startsWith('/api/') && ctx.path !== '/api' && ctx.path !== '/health';
}
/** 开发:反代到前端 dev server(含 HMR 的 WebSocket 升级) */
function proxyToDevServer(ctx, target) {
// koa 不再自己写响应,完全交给反代
ctx.respond = false;
const proxy = getProxy(target);
proxy.web(ctx.req, ctx.res, { target }, (err) => {
if (ctx.res.headersSent) return;
ctx.status = 502;
ctx.type = 'html';
ctx.body = `<h1>前端 dev server 连不上</h1><p>${err.message}</p>`
+ `<p>请先启动前端:<code>cd frontend; npm run dev</code>(目标 ${target})</p>`;
});
}
/** 按 target 缓存代理实例(同一个 target 复用连接池) */
const proxies = new Map();
function getProxy(target) {
if (proxies.has(target)) return proxies.get(target);
// ws: true —— 允许 `proxy.ws()` 把 HMR 的升级请求转过去
const proxy = httpProxy.createProxyServer({ changeOrigin: true, xfwd: true, ws: true });
proxy.on('error', (err, req, res) => {
// HTTP 请求的错误在 proxyToDevServer 的回调里处理;这里只兑底(避免 unhandled error 抛到进程)
if (res && !res.headersSent && res.writeHead) {
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
}
void err;
});
proxies.set(target, proxy);
return proxy;
}