Hello guys, newbie here.
I’m attempting to store data on the Postgres database deployed. My route.ts has two endpoints as following
app/guests/route.ts
// File: src/app/api/guest/route.ts
import { NextRequest, NextResponse } from 'next/server';
import prisma from '../../../lib/prisma';
export async function GET() {
try {
const guests = await prisma.guest.findMany();
return NextResponse.json(guests);
} catch (error) {
console.error('Error fetching guests:', error);
return NextResponse.error();
}
}
export async function PUT(request: NextRequest) {
try {
const { name, email, comment } = await request.json();
const newGuest = await prisma.guest.create({
data: {
name,
email,
comment,
},
});
console.log(newGuest);
return NextResponse.json(newGuest);
} catch (error) {
console.error('Error creating guest:', error);
return NextResponse.error();
}
}
On the client side I calls it in the way below:
const submitData = async (e: React.SyntheticEvent) => {
e.preventDefault();
try {
const response = await fetch('/api/guest', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name, email, comment }),
});
if (response.ok) {
const newGuest = await response.json();
setGuests((prevGuests) => [...prevGuests, newGuest]);
setSuccessMessage('Signed successfully, thank you! ===>' + response);
setErrorMessage('');
router.refresh();
} else {
throw new Error('Failed to submit data');
}
console.log(response);
} catch (error) {
setErrorMessage('Error submitting data. Please, try again. ===>' + error);
setSuccessMessage('');
console.error('Error:', error);
}
};
It’s a simpliest app to store and print data, without any client authentication.
I can fetch data with GET method without any issues, but the PUT method has been returning 500 Internal
error. Can you give me any idea for what is missing?
Thank you.