Next.js Discord

Discord Forum

API REQBODY ISSUE

Unanswered
Auth posted this in #help-forum
Open in Discord
so when i test my api using api tester it returns perfectly status code of 200 and user created but when i send data using frontend using axios it returns error code of 500

9 Replies

@Auth Click to see attachment
frontend
import { conn } from '@/db/conn';
import User from '@/models/userModel';
import { NextRequest, NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import { SendMail } from '@/helpers/mailer';

// Establish database connection
conn();

export async function POST(request: NextRequest) {
    try {
        // Parse request body
        const reqBody = await request.json();
        const { username, email, password } = reqBody;

        // Check if user with the given email already exists
        const existingUser = await User.findOne({ email });
        if (existingUser) {
            return NextResponse.json({ error: 'User already exists' }, { status: 400 });
        }

        // Hash the password
        const hashedPassword = await bcrypt.hash(password, 10);

        // Create a new user instance
        const newUser = new User({
            email,
            username,
            password: hashedPassword,
        });

        // Save the new user to the database
        const savedUser = await newUser.save();

        // Send verification email to the user
        await SendMail({ email, emailType: 'VERIFY', userId: savedUser._id });

        // Respond with success message
        return NextResponse.json({ message: "User registered successfully" }, { status: 200 });
    } catch (error: any) {
        // Handle any errors that occur during registration
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}