feat: 添加 API 基础地址配置和连接测试功能

This commit is contained in:
xiaozhou233 committed 2026-08-10 18:43:42 +08:00
1 parent 9dd1bc3cf9
commit e541a529d4
3 files changed
+140 -10

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
const STORAGE_KEY = 'workstation.apiBaseUrl'
function envApiBaseUrl(): string {
return import.meta.env.VITE_API_BASE_URL ?? ''
}
export function normalizeApiBaseUrl(url: string): string {
return url.trim().replace(/\/+$/, '')
}
export function getApiBaseUrl(): string {
try {
const saved = localStorage.getItem(STORAGE_KEY)
if (saved !== null && saved !== '') return normalizeApiBaseUrl(saved)
} catch {
// localStorage 不可用时退回环境变量
}
return envApiBaseUrl()
}
export function setApiBaseUrl(url: string): void {
const normalized = normalizeApiBaseUrl(url)
try {
if (normalized === '') {
localStorage.removeItem(STORAGE_KEY)
} else {
localStorage.setItem(STORAGE_KEY, normalized)
}
} catch {
// 忽略写入失败
}
}
export function resolveApiUrl(path: string): string {
const base = normalizeApiBaseUrl(getApiBaseUrl())
return `${base}${path}`
}
export function apiFetch(path: string, init?: RequestInit): Promise<Response> {
return fetch(resolveApiUrl(path), init)
}
+4 -5
View File
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { apiFetch } from '../lib/api'
interface CpuStats {
model: string
@@ -25,8 +26,6 @@ interface SystemStats {
os: OsStats
}
const API_BASE = import.meta.env.VITE_API_BASE_URL ?? ''
function formatUptime(seconds: number) {
const d = Math.floor(seconds / 86400)
const h = Math.floor((seconds % 86400) / 3600)
@@ -81,7 +80,7 @@ export default function Home() {
const [error, setError] = useState(false)
useEffect(() => {
fetch(`${API_BASE}/api/system/stats`)
apiFetch('/api/system/stats')
.then((res) => {
if (!res.ok) throw new Error('Failed to fetch stats')
return res.json()
@@ -111,7 +110,7 @@ export default function Home() {
<h2 className="text-center text-2xl font-semibold text-slate-900">系统状态</h2>
<p className="mt-1 text-center text-sm text-slate-500">
{error
? '无法获取系统信息,请确认后端服务已启动'
? '无法获取系统信息,请确认后端服务已启动,或在「设置」中配置服务器 API 地址'
: stats
? '实时运行状态一览'
: '正在获取系统信息…'}
@@ -193,7 +192,7 @@ export default function Home() {
</div>
) : (
<p className="py-16 text-center text-sm text-slate-400">
{error ? '无法获取系统信息,请确认后端服务已启动' : '正在获取系统信息…'}
{error ? '无法获取系统信息,请确认后端服务已启动,或在「设置」中配置服务器 API 地址' : '正在获取系统信息…'}
</p>
)}
</div>
+95 -5
View File
@@ -1,10 +1,100 @@
import { useState } from 'react'
import { getApiBaseUrl, normalizeApiBaseUrl, resolveApiUrl, setApiBaseUrl } from '../lib/api'
type TestStatus = 'idle' | 'testing' | 'ok' | 'fail'
export default function Settings() {
const [value, setValue] = useState(getApiBaseUrl())
const [saved, setSaved] = useState(getApiBaseUrl())
const [status, setStatus] = useState<TestStatus>('idle')
const [message, setMessage] = useState('')
const dirty = normalizeApiBaseUrl(value) !== saved
function handleSave() {
setApiBaseUrl(value)
setSaved(getApiBaseUrl())
setStatus('idle')
setMessage('')
}
async function handleTest() {
setStatus('testing')
setMessage('')
const base = normalizeApiBaseUrl(value)
const oldBase = getApiBaseUrl()
if (base !== oldBase) setApiBaseUrl(base)
try {
const res = await fetch(resolveApiUrl('/api/system/stats'))
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const data = await res.json()
const label = (data.os?.name as string | undefined) ?? '后端'
setStatus('ok')
setMessage(`${label} 连接正常`)
} catch {
setStatus('fail')
setMessage('连接失败,请检查地址是否正确以及后端服务是否已启动')
} finally {
if (base !== oldBase) setApiBaseUrl(oldBase)
}
}
return (
<section className="mx-auto flex min-h-[70vh] max-w-6xl flex-col items-center justify-center px-6 text-center">
<div className="grid size-16 place-items-center rounded-2xl bg-indigo-50 text-2xl">🚧</div>
<h1 className="mt-6 text-2xl font-semibold text-slate-900">设置</h1>
<p className="mt-2 text-slate-500">系统偏好与账号配置</p>
<p className="mt-4 rounded-md bg-slate-100 px-3 py-1 text-sm text-slate-500">页面建设中,敬请期待</p>
<section className="mx-auto min-h-[70vh] max-w-3xl px-6 py-12">
<h1 className="text-2xl font-semibold text-slate-900">设置</h1>
<p className="mt-1 text-sm text-slate-500">系统偏好与账号配置</p>
<div className="mt-8 rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<h2 className="text-base font-semibold text-slate-900">服务器 API 地址</h2>
<p className="mt-1 text-sm text-slate-500">
配置前端连接后端服务的 API 基础地址,留空则使用环境变量或本地代理
</p>
<label className="mt-5 block">
<span className="text-sm font-medium text-slate-700">API 基础地址</span>
<input
type="url"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="例如 http://your-server:9018,留空表示使用默认"
spellCheck={false}
className="mt-2 w-full rounded-md border border-slate-300 px-3 py-2 text-sm text-slate-900 outline-none transition-colors focus:border-indigo-500 focus:ring-2 focus:ring-indigo-100"
/>
</label>
<p className="mt-2 text-xs text-slate-400">
当前生效地址:{saved === '' ? '默认(本地代理)' : saved}
</p>
{message && (
<p
className={`mt-3 text-sm ${
status === 'ok' ? 'text-emerald-600' : status === 'fail' ? 'text-red-600' : 'text-slate-500'
}`}
>
{message}
</p>
)}
<div className="mt-6 flex flex-wrap gap-3">
<button
type="button"
onClick={handleTest}
disabled={status === 'testing'}
className="rounded-md border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-60"
>
{status === 'testing' ? '正在测试…' : '测试连接'}
</button>
<button
type="button"
onClick={handleSave}
disabled={!dirty}
className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-50"
>
保存
</button>
</div>
</div>
</section>
)
}