fake_shop/app/register/page.jsx

95 lines
3.1 KiB
React
Raw Normal View History

2025-02-10 19:24:19 +08:00
"use client";
import React, { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
export default function Register() {
const router = useRouter();
const [formData, setFormData] = useState({
username: "",
password: "",
});
const [error, setError] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
try {
const res = await fetch("/api/auth/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || "注册失败");
}
router.push("/login");
} catch (err) {
setError(err.message);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full space-y-8">
<div>
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
注册新账户
</h2>
</div>
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
{error && <div className="text-red-500 text-center">{error}</div>}
<div className="rounded-md shadow-sm -space-y-px">
<div>
<input
type="text"
required
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-yellow-500 focus:border-yellow-500 focus:z-10 sm:text-sm"
placeholder="用户名"
value={formData.username}
onChange={(e) =>
setFormData({ ...formData, username: e.target.value })
}
/>
</div>
<div>
<input
type="password"
required
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-yellow-500 focus:border-yellow-500 focus:z-10 sm:text-sm"
placeholder="密码"
value={formData.password}
onChange={(e) =>
setFormData({ ...formData, password: e.target.value })
}
/>
</div>
</div>
<div>
<button
type="submit"
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-yellow-400 hover:bg-yellow-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-yellow-500"
>
注册
</button>
</div>
<div className="text-sm text-center">
<Link
href="/login"
className="text-yellow-600 hover:text-yellow-500"
>
已有账户立即登录
</Link>
</div>
</form>
</div>
</div>
);
}