API - PUT Request is returning 500 [SOLVED]

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.

Hi, @ivanzanoth-gmailcom!

I can see in your title [SOLVED], is this all sorted now? :smile:

Helo @pawlean ,

yes, it was a trivial neglect in reading the logs.

Namely: Unique constraint failed on the fields: (email)

Thanks.

1 Like

It happens sometimes. :smile:

Thanks for coming back with your solution!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.