当某些用户尝试使用已注册的电子邮件进行注册时,我想显示漂亮的用户界面消息。 这是我的route.tsx(/api/auth/register/route.tsx)
import { NextResponse } from "next/server";
import prisma from "@/app/libs/prismadb";
import { hash } from "bcrypt";
export async function POST(request: Request){
try {
const {firstName, lastName, email, password} = await request.json();
console.log({firstName, lastName, email, password});
const userExist = await prisma.user.findFirst({
where: {
email: email
}
})
if(userExist){
//throw new Error("User with this email already exist");
return NextResponse.json({ message: "User with this email already exist" }, { status: 400 })
}
const hasPass = await hash(password, 12);
const user = await prisma.user.create({
data: {
firstName: firstName,
lastName: lastName,
email: email,
username: email,
hashedPassword: hasPass
}
})
return NextResponse.json({message: "success"});
} catch (error) {
console.log({error});
}
}
这是我的表单组件 form.tsx (app/register/form.tsx)
"use client"
import React, { FormEvent } from 'react'
const Form = () => {
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const formData = new FormData(e.currentTarget);
try {
const response = await fetch("api/auth/register", {
method: "POST",
body: JSON.stringify({
firstName: formData.get('firstName'),
lastName: formData.get('lastName'),
email: formData.get('email'),
password: formData.get('password'),
})
})
if (!response.ok) {
throw new Error("OOOOOOOPSS");
}
} catch (error) {
console.log(error);
}
}
return (
<form onSubmit={handleSubmit} className='w-full flex flex-col gap-5'>
<input className=' border-black bg-slate-300' type="text" name="firstName" id="firstName" placeholder='John' />
<input className=' border-black bg-slate-300' type="text" name="lastName" id="lastName" placeholder='Wick' />
<input className=' border-black bg-slate-300' type="email" name="email" id="email" placeholder='Email' />
<input className='border-black bg-slate-300' type="password" name="password" id="password" placeholder='Password' />
<button className=' bg-red-300' type="submit">Register</button>
</form>
)
}
export default Form
这是我的 page.tsx (app/register/page.tsx)
import Form from './form'
const page = () => {
return (
<div className='w-[300px] min-h-[400px] mx-auto mt-10'>
<Form />
</div>
)
}
export default page
最初我在 api 路由文件中抛出了一个错误。之后,我决定只返回带有消息的响应,但我无法从组件表单文件中的响应中获取消息。我只想知道向用户显示一条简单的警报消息(其中包含该电子邮件已注册的消息)的正确方法是什么
要将 toast 通知集成到 Next.js 应用程序中以显示错误消息,您可以使用像 React-toastify 这样的库。以下是修改代码以使用 Toast 通知的方法:
首先,安装react-toastify:
npm install react-toastify
然后,在 /api/auth/register/route.tsx 文件中,修改代码以使用 toast 通知:
import { NextApiRequest, NextApiResponse } from 'next';
import { toast } from 'react-toastify';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
try {
// Check if the email is already registered (pseudo code)
const emailExists = await checkIfEmailExists(req.body.email);
if (emailExists) {
// Email is already registered, send a custom error response
return res.status(400).json({ error: 'Email is already registered.' });
}
// Proceed with registration if email is not registered
// Your registration logic goes here
// Send success response if registration is successful
return res.status(200).json({ message: 'Registration successful.' });
} catch (error) {
// Handle other errors
console.error('Error:', error);
// Display error message using toast
toast.error('An error occurred. Please try again later.');
return res.status(500).json({ error: 'Internal server error.' });
}
} else {
// Method not allowed
return res.status(405).json({ error: 'Method not allowed' });
}
}
async function checkIfEmailExists(email: string): Promise<boolean> {
// Your logic to check if the email is already registered
// Return true if email exists, false otherwise (pseudo code)
return await yourDatabaseQueryToCheckIfEmailExists(email);
}
在处理HTTP请求的客户端代码中(例如,调用registerUser函数的地方),您可以监听toast消息并使用react-toastify显示它们:
// Example using Axios for HTTP requests
import axios from 'axios';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
const registerUser = async (userData) => {
try {
const response = await axios.post('/api/auth/register', userData);
// Registration successful, show success message to user
toast.success(response.data.message);
} catch (error) {
// Handle error response
if (error.response && error.response.data && error.response.data.error) {
// Display error message to user
toast.error(error.response.data.error);
} else {
// Handle other errors
console.error('An error occurred:', error.message);
toast.error('An error occurred. Please try again later.');
}
}
};
现在,当注册过程中发生错误时,会出现 Toast 通知 将出现在客户端并带有相应的错误消息。