fix: vite dev 自动跳转到带尾斜杠的 base 并静默处理 API 重启期代理报错
- admin/client 新增 redirectToBase 插件,访问 /admin 或 / 自动 302 到 /admin/(client 同理 /trace/) - admin /api 代理增加错误处理,API 重启空档返回 503 让前端静默重试,避免 ECONNREFUSED 堆栈刷屏
This commit is contained in:
+46
-11
@@ -1,10 +1,51 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import { defineConfig, type Plugin } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import { fileURLToPath, URL } from 'node:url';
|
||||
import type { ServerResponse } from 'node:http';
|
||||
|
||||
const BASE = process.env.VITE_BASE || '/admin/';
|
||||
|
||||
// dev 下访问根路径或不带尾斜杠的 base(如 /admin)时自动 302 到 /admin/,
|
||||
// 避免 vite 只提示 "did you mean /admin/" 而不跳转。
|
||||
function redirectToBase(base: string): Plugin {
|
||||
const baseNoSlash = base.replace(/\/$/, '');
|
||||
return {
|
||||
name: 'redirect-to-base',
|
||||
configureServer(server) {
|
||||
server.middlewares.use((req, res, next) => {
|
||||
const url = req.url || '/';
|
||||
const path = url.split('?')[0];
|
||||
if (path === '/' || path === baseNoSlash) {
|
||||
const query = url.slice(path.length);
|
||||
res.statusCode = 302;
|
||||
res.setHeader('Location', base + query);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// API 重启期间(如安装完成自动切换)代理连接被拒属正常,返回 503 让前端静默重试,
|
||||
// 避免抛出大段 ECONNREFUSED 堆栈。
|
||||
function onProxyError(proxy: { on: (e: string, cb: (...a: unknown[]) => void) => void }): void {
|
||||
proxy.on('error', (...args: unknown[]) => {
|
||||
const res = args[2] as (ServerResponse & { headersSent?: boolean }) | undefined;
|
||||
if (!res) return;
|
||||
if (!res.headersSent && typeof res.writeHead === 'function') {
|
||||
res.writeHead(503, { 'Content-Type': 'application/json' });
|
||||
}
|
||||
if (typeof res.end === 'function') {
|
||||
res.end('{"code":1005,"message":"service restarting","data":null}');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
base: process.env.VITE_BASE || '/admin/',
|
||||
plugins: [vue()],
|
||||
base: BASE,
|
||||
plugins: [vue(), redirectToBase(BASE)],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
@@ -15,14 +56,8 @@ export default defineConfig({
|
||||
port: 5173,
|
||||
host: true,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/uploads': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/api': { target: 'http://localhost:3000', changeOrigin: true, configure: onProxyError },
|
||||
'/uploads': { target: 'http://localhost:3000', changeOrigin: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user