移除 next.config.js 中的 standalone 输出配置,添加 lib/api-client.ts 封装 fetch 请求, 自动为所有 API 调用添加配置的 basePath。更新所有页面和组件中的 fetch 调用以使用新的 fetchApi 函数, 确保在部署到子路径时 API 请求能正确工作。同时调整 tsconfig.json 的格式并修复项目创建时的字段名。
82 lines
2.7 KiB
TypeScript
82 lines
2.7 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useState } from 'react';
|
|
import { useRouter } from 'next/navigation';
|
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Input } from '@/components/ui/input';
|
|
import { Label } from '@/components/ui/label';
|
|
import { toast } from 'sonner';
|
|
import { useUser } from '@/components/user-context';
|
|
import { fetchApi } from '@/lib/api-client';
|
|
|
|
const DEFAULT_USERNAME = 'baicaimiao';
|
|
const DEFAULT_PASSWORD = 'baicaimiao123';
|
|
|
|
export default function LoginPage() {
|
|
const router = useRouter();
|
|
const { isAuthenticated, isInitialized, isLoading, refreshMe } = useUser();
|
|
const [username, setUsername] = useState(DEFAULT_USERNAME);
|
|
const [password, setPassword] = useState(DEFAULT_PASSWORD);
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
|
|
useEffect(() => {
|
|
if (isInitialized && !isLoading && isAuthenticated) {
|
|
router.replace('/');
|
|
}
|
|
}, [isAuthenticated, isInitialized, isLoading, router]);
|
|
|
|
const onSubmit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
setIsSubmitting(true);
|
|
try {
|
|
const res = await fetchApi('/api/auth/login', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ username, password }),
|
|
});
|
|
|
|
const data = await res.json().catch(() => ({}));
|
|
if (!res.ok) {
|
|
throw new Error(data?.error || '登录失败');
|
|
}
|
|
|
|
const userId = data?.user?.id as string | undefined;
|
|
if (!userId) throw new Error('登录失败');
|
|
|
|
await refreshMe();
|
|
toast.success('登录成功');
|
|
router.replace('/');
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : '登录失败');
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="min-h-screen flex items-center justify-center bg-slate-50 px-4">
|
|
<Card className="w-full max-w-md">
|
|
<CardHeader>
|
|
<CardTitle>登录</CardTitle>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<form onSubmit={onSubmit} className="space-y-4">
|
|
<div>
|
|
<Label htmlFor="username">账号</Label>
|
|
<Input id="username" value={username} onChange={(e) => setUsername(e.target.value)} />
|
|
</div>
|
|
<div>
|
|
<Label htmlFor="password">密码</Label>
|
|
<Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
|
|
</div>
|
|
<Button type="submit" className="w-full bg-teal-600 hover:bg-teal-700" disabled={isSubmitting}>
|
|
{isSubmitting ? '登录中...' : '登录'}
|
|
</Button>
|
|
</form>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|