feat(frontend): 新增蓝绿发布脚本与生产 API 地址

发布:
- 新增 scripts/deploy.mjs、rollback.mjs、init-config.mjs 与 scripts/remote/{deploy,rollback}.sh
  · 服务器上按 releases/<版本号> 存放,current 软链原子切换,发布/回滚都不中断服务
  · 切换前校验 index.html 与引用的 /assets 资源完整,并补齐历史版本静态资源(旧 chunk 不 404)
  · 真实配置 scripts/deploy.config.json 已加入忽略清单,模板 deploy.config.example.json 入库
- package.json 增加 deploy / rollback / deploy:init

接口地址:
- 新增 .env.production(VITE_API_BASE_URL=https://api.oms.gztbyc.com/api)与 .env.development
  (/api,继续走 vite 代理到本地 6090)
- request.ts 的 baseURL 改为读 VITE_API_BASE_URL;env.d.ts 声明 ImportMetaEnv
- 新增 utils/media.ts#mediaUrl:跨域部署时把后端返回的相对地址(/api/files/raw/…)
  补全为 API 站点绝对地址,用于 ImageUploader、商品列表图片、主体账号头像渲染

工程:
- tsconfig 去掉已弃用的 baseUrl(TS 7 将移除;paths 自 TS 4.1 起不再依赖它)
- .gitignore 增加 dist.tar.gz 与真实部署配置
This commit is contained in:
liufumingren 2026-09-14 22:14:27 +08:00
parent fc58f79b42
commit 441659d303
18 changed files with 473 additions and 9 deletions

View File

@ -0,0 +1,3 @@
# 开发环境:与前端同源,由 vite dev server 代理到本地后端
# (见 vite.config.ts 的 server.proxy,默认 http://localhost:6090)
VITE_API_BASE_URL=/api

9
frontend/.env.production Normal file
View File

@ -0,0 +1,9 @@
# 生产环境后端 API 地址
# 前端站点 oms.gztbyc.com 与后端 API 站点 api.oms.gztbyc.com 不同源,这里直连 API 站点。
#
# 注意:
# 1. 必须带 /api 前缀(后端所有接口路由都在 /api 下,如 https://api.oms.gztbyc.com/api/auth/login)
# 2. 必须与前端站点同协议(HTTPS 站点调 http:// 会被浏览器按「混合内容(Mixed Content)」拦截)
# 3. 跨域请求由后端 CORS 中间件放行,白名单见 backend/app/middleware/cors.js
# (默认已放行 http/https 的 oms.gztbyc.com,可用后端环境变量 CORS_ORIGINS 覆盖)
VITE_API_BASE_URL=https://api.oms.gztbyc.com/api

4
frontend/.gitignore vendored
View File

@ -10,6 +10,10 @@ dist
dist-ssr
*.local
# 部署产物与真实部署配置(含服务器/密钥信息,不入库;模板见 scripts/deploy.config.example.json)
dist.tar.gz
/scripts/deploy.config.json
# Editor / OS
.DS_Store
.idea

6
frontend/env.d.ts vendored
View File

@ -1,5 +1,11 @@
/// <reference types="vite/client" />
/** 环境变量(各环境取值见 .env.development / .env.production) */
interface ImportMetaEnv {
/** 后端 API 基础地址,必须带 /api 前缀,如 http://api.oms.gztbyc.com/api */
readonly VITE_API_BASE_URL?: string
}
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, unknown>

View File

@ -6,7 +6,10 @@
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview"
"preview": "vite preview",
"deploy": "node ./scripts/deploy.mjs",
"rollback": "node ./scripts/rollback.mjs",
"deploy:init": "node ./scripts/init-config.mjs"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.1",

100
frontend/scripts/DEPLOY.md Normal file
View File

@ -0,0 +1,100 @@
# OMS 前端蓝绿发布
发布方式与 WMS 前端一致:服务器上按版本目录存放,`current` 软链接指向当前线上版本,切换是原子的,因此**发布/回滚都不中断服务**。
## 目录结构
```
frontend/
├─ scripts/
│ ├─ deploy.mjs # 本地:构建 → 打包 → 上传 → 触发远程切换
│ ├─ rollback.mjs # 本地:把 current 切回上一个版本
│ ├─ init-config.mjs # 生成本地部署配置
│ ├─ deploy.config.example.json # 配置模板(提交 git)
│ ├─ deploy.config.json # 真实配置(.gitignore 排除,禁止提交)
│ └─ remote/
│ ├─ deploy.sh # 服务器端执行:解压 → 校验 → 原子切换 → 清理
│ └─ rollback.sh # 服务器端执行:原子回滚
```
服务器上的布局(`basePath` = `/www/wwwroot/oms.gztbyc.com`):
```
/www/wwwroot/oms.gztbyc.com/
├─ releases/
│ ├─ v20260914_153000_12345/ # 各版本静态文件(index.html + assets/…)
│ └─ ...
└─ current -> releases/v2026... # 软链接,Nginx 站点根目录指向它
```
## 服务器前置条件(仅首次)
```bash
mkdir -p /www/wwwroot/oms.gztbyc.com/releases
```
宝塔面板:站点 `oms.gztbyc.com` 的**网站目录**要设为 `/www/wwwroot/oms.gztbyc.com/current`
(而不是 `.../oms.gztbyc.com`),其余 `index.html`、`/api` 反向代理到后端等配置保持不变。
不需要 `chown` 到 www 用户,但站点目录需对 ssh 用户可写(示例用 `root`)。
## 使用
```bash
cd frontend
# 首次:生成本地部署配置,然后按实际服务器信息修改
npm run deploy:init
# 发布(内部执行 npm run build → 打包 → 上传 → 原子切换)
npm run deploy
# 跳过构建,直接发布现有 dist(调试用)
npm run deploy -- --skip-build
# 回滚到上一个版本(不构建、不上传,秒级)
npm run rollback
```
## 配置项(`scripts/deploy.config.json`)
| 字段 | 说明 |
| --- | --- |
| `user` | ssh 登录用户 |
| `ip` | 服务器 IP |
| `basePath` | 站点根目录,`releases/` 与 `current` 都在其下 |
| `keepReleases` | 服务器保留的最近版本数(默认 5,超出的自动清理,不会删除 current 指向的版本) |
| `siteHost` | 发版后健康检查用的域名(本机 curl 带 Host 头访问 `https://127.0.0.1/`,仅打印状态码,不阻断发布) |
| `sshKey` | 私钥:绝对路径或 `~/.ssh` 下的文件名;留空则用 ssh 默认密钥/agent |
## 发布流程细节(`remote/deploy.sh`)
1. 解压到独立的新版本目录,**全程不触碰线上目录**
2. 校验 `index.html` 非空,且 `index.html` 中引用的 `/assets/*.js|css` 都存在,否则中止(线上版本不受影响)
3. 把最近若干个历史版本中、本版本缺失的文件并入新版本 —— 保证切换后仍停留在旧版页面的用户动态加载旧 chunk 不 404(无感切换的关键)
4. `ln -sfn` 建临时软链 + `mv -Tf` 改名,原子切换
5. 健康检查(仅提示)
6. 清理超出 `keepReleases` 的旧版本
## 注意
- `scripts/deploy.config.json` **不要提交 git**(已在 `frontend/.gitignore` 中排除),只提交 `deploy.config.example.json` 模板。
- 需要本机具备 `ssh`、`scp`、`tar`(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。
- 后端 `oms` 服务不在本脚本范围内,本脚本只发布前端静态文件。
## 前后端域名与跨域(CORS)
| 站点 | 说明 |
| --- | --- |
| `oms.gztbyc.com` | 前端静态站点,由本脚本发布(Nginx 根目录指向 `current`) |
| `api.oms.gztbyc.com` | 后端 API 站点,Nginx 反代到 egg 后端(端口 6090),接口路由前缀 `/api` |
- 前端 API 地址由构建期环境变量 `VITE_API_BASE_URL` 决定:
- 生产 `${VITE_API_BASE_URL}=http://api.oms.gztbyc.com/api`(`frontend/.env.production`)
- 开发 `VITE_API_BASE_URL=/api`(`frontend/.env.development`,由 vite dev server 代理到 `http://localhost:6090`)
- 两个域名**不同源**,跨域请求由后端 `backend/app/middleware/cors.js` 按白名单放行
(默认已含 http/https 的 `oms.gztbyc.com`,可用后端环境变量 `CORS_ORIGINS` 覆盖)。
- 后端返回的图片/头像地址是相对路径(`/api/files/raw/...`),前端渲染时由
`frontend/src/utils/media.ts` 的 `mediaUrl()` 补全为 API 站点绝对地址。
- ⚠️ 若前端站点改用 HTTPS 访问,`VITE_API_BASE_URL` 必须同步改为 `https://api.oms.gztbyc.com/api`,
否则浏览器会按「混合内容(Mixed Content)」拦截请求。

View File

@ -0,0 +1,8 @@
{
"user": "root",
"ip": "112.124.21.102",
"basePath": "/www/wwwroot/oms.gztbyc.com",
"keepReleases": 5,
"siteHost": "oms.gztbyc.com",
"sshKey": "C:\\Users\\lfmingren\\.ssh\\112.124.21.102_id_ed25519"
}

136
frontend/scripts/deploy.mjs Normal file
View File

@ -0,0 +1,136 @@
#!/usr/bin/env node
/**
* OMS 前端蓝绿发布脚本(Windows / macOS / Linux 通用)
*
* 发布原理:
* 1. 本地构建 dist,压缩后上传到服务器 `${basePath}/releases/<版本号>/`(全新目录,不触碰线上目录)
* 2. 服务器上解压并做完整性校验,再把历史版本的静态资源补齐(旧 chunk 不 404)
* 3. 通过 `current` 软链接「先建临时链接再 mv 改名」原子切换,切换瞬间服务不中断
* 4. 健康检查(仅提示)并清理超出保留数量的旧版本
*
* 依赖本机已安装:ssh、scp、tar(Windows 10 1803+ 自带 OpenSSH 客户端与 bsdtar)。
*
* 用法:
* npm run deploy 构建 + 发布
* npm run deploy -- --skip-build 跳过本地构建,直接发布现有 dist(调试用)
*/
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PROJECT_ROOT = path.resolve(__dirname, '..');
// --- 配置(读取独立配置文件,该文件不纳入版本控制) ---
const CONFIG_PATH = path.join(__dirname, 'deploy.config.json');
const EXAMPLE_PATH = path.join(__dirname, 'deploy.config.example.json');
if (!existsSync(CONFIG_PATH)) {
console.error('❌ 缺少配置文件 scripts/deploy.config.json');
console.error(` 请复制 scripts/deploy.config.example.json 为 scripts/deploy.config.json 并修改其中参数。`);
console.error(` 模板路径:${EXAMPLE_PATH}`);
process.exit(1);
}
const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
// --- 配置校验 ---
const REQUIRED_KEYS = ['user', 'ip', 'basePath', 'siteHost'];
const missingKeys = REQUIRED_KEYS.filter((k) => !config[k]);
if (missingKeys.length) {
console.error(`❌ scripts/deploy.config.json 缺少必填项:${missingKeys.join(', ')}`);
console.error(' 参考 scripts/deploy.config.example.json 补齐。');
process.exit(1);
}
const SKIP_BUILD = process.argv.includes('--skip-build');
const USER = config.user;
const IP = config.ip; // 服务器 IP
const BASE_PATH = config.basePath; // 站点在服务器上的存放路径(releases/current 都在其下)
const KEEP_RELEASES = Number(config.keepReleases) > 0 ? Number(config.keepReleases) : 5; // 服务器保留的最近版本数
const SITE_HOST = config.siteHost; // 发版后健康检查域名
const LOCAL_DIST = path.join(PROJECT_ROOT, 'dist');
const SSH_KEY = resolveSshKey(config.sshKey);
const SSH_OPTS = ['-o', 'StrictHostKeyChecking=no', ...(SSH_KEY ? ['-i', SSH_KEY] : [])];
const HOST = `${USER}@${IP}`;
const TARBALL = 'dist.tar.gz';
const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const RELEASE_NAME = `v${timestamp()}_${process.pid}`; // 版本号(带 PID,避免并发/重复发布冲突)
const REMOTE_RELEASE = `${BASE_PATH}/releases/${RELEASE_NAME}`;
function timestamp() {
const d = new Date();
const p = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}_${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
}
/** sshKey 支持「绝对路径」与「~/.ssh 下的文件名」;留空则用 ssh 默认密钥/agent */
function resolveSshKey(value) {
if (!value) return '';
if (value.startsWith('~')) return path.join(os.homedir(), value.slice(1));
return path.isAbsolute(value) ? value : path.join(os.homedir(), '.ssh', value);
}
function run(cmd, args, opts = {}) {
// Windows 下 .cmd/.bat(如 npm.cmd)不能直接用 spawnSync 执行(报 EINVAL):
// 优先用 node 直接运行 npm-cli.js(无 shell、无 DEP0190 警告),否则回退到 shell: true
const isWinCmd = process.platform === 'win32' && /\.(cmd|bat)$/i.test(cmd);
let res;
if (isWinCmd) {
const npmCli = process.env.npm_execpath;
if (npmCli && /npm-cli\.js$/i.test(npmCli)) {
res = spawnSync(process.execPath, [npmCli, ...args], { stdio: 'inherit', ...opts });
} else {
res = spawnSync(cmd, args, { stdio: 'inherit', shell: true, ...opts });
}
} else {
res = spawnSync(cmd, args, { stdio: 'inherit', ...opts });
}
if (res.error) {
console.error(`❌ 无法执行命令 ${cmd}: ${res.error.message}`);
if (res.error.code === 'ENOENT') {
console.error(' 请确认本机已安装对应命令(ssh/scp/tar)。Windows 10 1803+ 自带 OpenSSH 客户端与 tar。');
}
process.exit(1);
}
if (res.status !== 0) process.exit(res.status ?? 1);
}
console.log(`🚀 开始发布 OMS 前端,版本: ${RELEASE_NAME}`);
console.log(` 目标:${HOST}:${REMOTE_RELEASE}`);
try {
// 1. 本地打包(失败立即中止,防止把坏产物发到线上)
if (SKIP_BUILD) {
console.log('⏭️ 已跳过本地构建(--skip-build)');
} else {
run(NPM, ['run', 'build'], { cwd: PROJECT_ROOT });
}
// 2. 校验本地产物完整性
if (!existsSync(path.join(LOCAL_DIST, 'index.html')) || !existsSync(path.join(LOCAL_DIST, 'assets'))) {
console.error('❌ 本地构建产物不完整(缺少 index.html 或 assets),中止发布');
process.exit(1);
}
// 3. 压缩并上传到服务器上的新版本目录(全程不触碰 current 指向的线上目录)
run('tar', ['-czf', TARBALL, '-C', LOCAL_DIST, '.'], { cwd: PROJECT_ROOT });
run('ssh', [...SSH_OPTS, HOST, `mkdir -p '${REMOTE_RELEASE}'`]);
run('scp', [...SSH_OPTS, path.join(PROJECT_ROOT, TARBALL), `${HOST}:${REMOTE_RELEASE}/${TARBALL}`]);
// 4. 远程:解压 → 校验 → 补齐旧资源 → 原子切换 → 健康检查 → 清理
const remoteScript = readFileSync(path.join(__dirname, 'remote', 'deploy.sh'), 'utf8');
run(
'ssh',
[...SSH_OPTS, HOST, `RELEASE='${REMOTE_RELEASE}' BASE='${BASE_PATH}' KEEP=${KEEP_RELEASES} HOST='${SITE_HOST}' bash -s`],
{ input: remoteScript, stdio: ['pipe', 'inherit', 'inherit'] }
);
console.log(`✨ 发布成功!当前版本: ${RELEASE_NAME}`);
} finally {
// 无论成功失败都清理本地临时压缩包
rmSync(path.join(PROJECT_ROOT, TARBALL), { force: true });
}

View File

@ -0,0 +1,24 @@
#!/usr/bin/env node
/**
* 初始化部署配置:把 scripts/deploy.config.example.json 复制为 scripts/deploy.config.json。
* deploy.config.json 含服务器/密钥信息,已被 .gitignore 排除,不要提交。
*
* 用法:npm run deploy:init
*/
import { copyFileSync, existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const EXAMPLE_PATH = path.join(__dirname, 'deploy.config.example.json');
const CONFIG_PATH = path.join(__dirname, 'deploy.config.json');
if (existsSync(CONFIG_PATH)) {
console.log('ℹ️ scripts/deploy.config.json 已存在,未覆盖。');
console.log(` 如需重新生成,请先删除该文件:${CONFIG_PATH}`);
process.exit(0);
}
copyFileSync(EXAMPLE_PATH, CONFIG_PATH);
console.log('✅ 已生成 scripts/deploy.config.json');
console.log(' 请按实际服务器信息修改其中的 user / ip / basePath / siteHost / sshKey,然后再执行 npm run deploy。');

View File

@ -0,0 +1,51 @@
set -euo pipefail
cd "$RELEASE"
# 4.1 解压
tar -xzf dist.tar.gz
rm -f dist.tar.gz
# 4.2 完整性校验:新版本必须完整,残缺则取消切换(当前线上版本不受影响)
if [ ! -s index.html ]; then
echo "❌ 新版本 index.html 缺失或为空,取消切换"
exit 1
fi
missing=""
for ref in $(grep -oE '/assets/[A-Za-z0-9._-]+\.(js|css)' index.html | sort -u || true); do
[ -f ".$ref" ] || missing="$missing $ref"
done
if [ -n "$missing" ]; then
echo "❌ 新版本缺少以下资源,取消切换:$missing"
exit 1
fi
# 4.3 补齐旧版本静态资源(无感切换的关键)
# 把最近几个历史版本中、本版本缺失的文件(旧 chunk、图片等)合并进新版本,
# 保证切换后正在使用旧版本页面的用户,动态 import 旧资源依然能找到,不会 404。
for src in $(ls -td "$BASE"/releases/*/ 2>/dev/null | head -n "$((KEEP + 1))" || true); do
[ -d "$src" ] || continue
[ "$(readlink -f "$src" 2>/dev/null)" = "$(pwd)" ] && continue
cp -rn "$src/." "$RELEASE/" 2>/dev/null || true
done
# 4.4 原子切换软链接(先建临时链接再改名,切换瞬间服务不中断)
ln -sfn "$RELEASE" "$BASE/current_new"
mv -Tf "$BASE/current_new" "$BASE/current"
# 4.5 健康检查(仅提示,不阻断发布)
if command -v curl >/dev/null 2>&1; then
code="$(curl -skL -o /dev/null -w '%{http_code}' -H "Host: $HOST" "https://127.0.0.1/" 2>/dev/null || true)"
echo "ℹ️ 新版本首页 HTTP 状态码: ${code:-未知}"
fi
# 4.6 清理旧版本:只保留最近 KEEP 个,且绝不删除 current 指向的版本
CURRENT_TARGET="$(readlink -f "$BASE/current" 2>/dev/null || true)"
count=0
for d in $(ls -t "$BASE/releases" 2>/dev/null || true); do
count=$((count+1))
[ "$count" -le "$KEEP" ] && continue
target="$(readlink -f "$BASE/releases/$d" 2>/dev/null || echo "$BASE/releases/$d")"
[ "$target" = "$CURRENT_TARGET" ] && continue
rm -rf "$BASE/releases/$d"
done

View File

@ -0,0 +1,15 @@
set -euo pipefail
# 获取 releases 目录下按时间排序的倒数第二个版本(当前版本的上一版)
PREVIOUS_VERSION="$(ls -dt "$BASE"/releases/*/ 2>/dev/null | sed -n '2p' || true)"
if [ -z "$PREVIOUS_VERSION" ]; then
echo "❌ 找不到可回滚的历史版本"
exit 1
fi
# 原子切换软链接(与发版脚本一致,切换瞬间服务不中断)
ln -sfn "$PREVIOUS_VERSION" "$BASE/current_new"
mv -Tf "$BASE/current_new" "$BASE/current"
echo "✅ 已回滚至: $PREVIOUS_VERSION"

View File

@ -0,0 +1,66 @@
#!/usr/bin/env node
/**
* OMS 前端蓝绿回滚脚本(Windows / macOS / Linux 通用)
*
* 回滚原理:把服务器上的 `current` 软链接原子切回 releases 里按时间排序的上一个版本。
* 不做构建、不重新上传,秒级完成。
*
* 依赖本机已安装:ssh(Windows 10 1803+ 自带 OpenSSH 客户端)。
*
* 用法:
* npm run rollback
*/
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// --- 配置(读取独立配置文件,该文件不纳入版本控制) ---
const CONFIG_PATH = path.join(__dirname, 'deploy.config.json');
if (!existsSync(CONFIG_PATH)) {
console.error('❌ 缺少配置文件 scripts/deploy.config.json');
console.error(' 请复制 scripts/deploy.config.example.json 为 scripts/deploy.config.json 并修改其中参数。');
process.exit(1);
}
const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
const REQUIRED_KEYS = ['user', 'ip', 'basePath'];
const missingKeys = REQUIRED_KEYS.filter((k) => !config[k]);
if (missingKeys.length) {
console.error(`❌ scripts/deploy.config.json 缺少必填项:${missingKeys.join(', ')}`);
process.exit(1);
}
const USER = config.user;
const IP = config.ip; // 服务器 IP
const BASE_PATH = config.basePath; // 站点在服务器上的存放路径
const SSH_KEY = resolveSshKey(config.sshKey);
const SSH_OPTS = ['-o', 'StrictHostKeyChecking=no', ...(SSH_KEY ? ['-i', SSH_KEY] : [])];
const HOST = `${USER}@${IP}`;
/** sshKey 支持「绝对路径」与「~/.ssh 下的文件名」;留空则用 ssh 默认密钥/agent */
function resolveSshKey(value) {
if (!value) return '';
if (value.startsWith('~')) return path.join(os.homedir(), value.slice(1));
return path.isAbsolute(value) ? value : path.join(os.homedir(), '.ssh', value);
}
console.log('⏪ 正在回滚 OMS 前端到上一个版本...');
const remoteScript = readFileSync(path.join(__dirname, 'remote', 'rollback.sh'), 'utf8');
const res = spawnSync('ssh', [...SSH_OPTS, HOST, `BASE='${BASE_PATH}' bash -s`], {
input: remoteScript,
stdio: ['pipe', 'inherit', 'inherit'],
});
if (res.error) {
console.error(`❌ 无法执行 ssh: ${res.error.message}`);
if (res.error.code === 'ENOENT') {
console.error(' 请确认本机已安装 OpenSSH 客户端(Windows 10 1803+ 自带)。');
}
process.exit(1);
}
process.exit(res.status ?? 1);

View File

@ -1,7 +1,8 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { checkFiles, hashFile, uploadFile, type FileItem } from '@/api/file'
import { mediaUrl } from '@/utils/media'
/** el-upload 自定义上传回调参数(仅用到 file / onProgress / onSuccess / onError) */
interface UploadRequestOptions {
@ -40,6 +41,9 @@ watch(
const uploading = ref(false)
const percent = ref(0)
/** 预览地址:后端返回的是相对地址(/api/files/raw/…),跨域部署时需补全为 API 站点地址 */
const previewUrls = computed(() => urls.value.map(mediaUrl))
function update() {
emit('update:modelValue', [ ...urls.value ])
}
@ -118,9 +122,9 @@ async function handleRequest(options: UploadRequestOptions) {
<div class="image-grid">
<div v-for="(url, index) in urls" :key="`${url}-${index}`" class="image-item">
<el-image
:src="url"
:src="mediaUrl(url)"
fit="cover"
:preview-src-list="urls"
:preview-src-list="previewUrls"
:initial-index="index"
preview-teleported
/>

View File

@ -0,0 +1,33 @@
/**
* 后端静态资源地址归一化
*
* 后端返回的是相对地址(如 /api/files/raw/1/2026/09/14/xxx.png,见 backend/config 的 upload.urlPrefix),
* 生产环境前端站点(oms.gztbyc.com)与 API 站点(api.oms.gztbyc.com)不同源,
* 相对地址会被解析到前端站点域名下而 404,因此渲染前要补上 API 站点的 origin。
*
* 本地开发 VITE_API_BASE_URL=/api(同源,走 vite 代理),原样返回。
* 注意:只在「渲染」时使用,写回接口的字段仍要保存后端原始值。
*/
const API_BASE_URL = (import.meta.env.VITE_API_BASE_URL || '/api').trim().replace(/\/+$/, '')
/** API 基础地址的 origin;相对地址(如 /api)时为空串 */
const API_ORIGIN = /^https?:\/\//i.test(API_BASE_URL)
? API_BASE_URL.replace(/^(https?:\/\/[^/]+).*$/i, '$1')
: ''
/** 已是绝对地址的判定:http(s)://、//、data:、blob: 等带协议的地址 */
const ABSOLUTE_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i
/**
* 把后端返回的相对资源地址补全为绝对地址
* @param url 后端返回的地址(相对或绝对,可为空)
* @return 可直接用于 img/src 预览的地址;空值返回空串
*/
export function mediaUrl(url?: string | null): string {
if (!url) return ''
const value = String(url).trim()
if (!value) return ''
if (ABSOLUTE_RE.test(value)) return value
if (!API_ORIGIN) return value
return `${API_ORIGIN}${value.startsWith('/') ? value : `/${value}`}`
}

View File

@ -36,7 +36,8 @@ export function clearToken(): void {
}
const service = axios.create({
baseURL: '/api',
// 后端 API 基础地址:开发环境 /api(vite 代理到本地后端),生产环境走 .env.production
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
timeout: 15000,
})

View File

@ -13,6 +13,7 @@ import ImageUploader from '@/components/ImageUploader.vue'
import ListPager from '@/components/ListPager.vue'
import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage'
import { formatDateTime } from '@/utils/datetime'
import { mediaUrl } from '@/utils/media'
const query = reactive({
page: 1,
@ -235,7 +236,7 @@ onMounted(fetchList)
<el-table-column label="用户" min-width="180">
<template #default="{ row }">
<div class="user-cell">
<el-avatar :size="28" :src="row.avatar || undefined">{{ avatarText(row) }}</el-avatar>
<el-avatar :size="28" :src="mediaUrl(row.avatar) || undefined">{{ avatarText(row) }}</el-avatar>
<span>{{ userLabel(row) }}</span>
</div>
</template>

View File

@ -12,6 +12,7 @@ import ImageUploader from '@/components/ImageUploader.vue'
import DataTable from '@/components/DataTable.vue'
import ListPager from '@/components/ListPager.vue'
import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage'
import { mediaUrl } from '@/utils/media'
const query = reactive({
page: 1,
@ -275,10 +276,10 @@ onMounted(fetchList)
<template #default="{ row }">
<el-image
v-if="coverOf(row)"
:src="coverOf(row)"
:src="mediaUrl(coverOf(row))"
fit="cover"
style="width: 44px; height: 44px; border-radius: 4px"
:preview-src-list="imagesOf(row)"
:preview-src-list="imagesOf(row).map(mediaUrl)"
preview-teleported
/>
<span v-else>-</span>

View File

@ -16,7 +16,6 @@
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}