PersonalWebApplication/Client/src/api/auth.ts

39 lines
1.1 KiB
TypeScript
Raw Normal View History

// 登录接口封装。后端基址默认本机 8080可用 VITE_API_BASE 覆盖
// (与 useSystemStats 保持一致)。
const API_BASE =
(import.meta.env.VITE_API_BASE as string | undefined) ?? 'http://localhost:8080'
export interface LoginResult {
ok: boolean
username: string
token: string
}
/**
* /
* - 200 token
* - 401
* - fetch
*/
export async function login(username: string, password: string): Promise<LoginResult> {
let res: Response
try {
res = await fetch(`${API_BASE}/api/web/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
})
} catch {
throw new Error('Cannot reach the server. Please make sure the backend is running.')
}
if (res.status === 401) {
throw new Error('Incorrect username or password')
}
if (!res.ok) {
throw new Error(`Sign-in failed (HTTP ${res.status})`)
}
return (await res.json()) as LoginResult
}