Search code examples
sqltypescriptnext.jsprismanext.js13

how can I insert database into my nextjs program


The thing is I was practicing postgresql to nextjs integration but when I try to create an account it has this error 405 according to the else condition.

this is the error in the browser console:

page.tsx:14 
        
        
        POST http://localhost:3000/api/auth/signup net::ERR_ABORTED 405 (Method Not Allowed)
handleSubmit @ page.tsx:14
callCallback @ react-dom.development.js:19462
invokeGuardedCallbackImpl @ react-dom.development.js:19511
invokeGuardedCallback @ react-dom.development.js:19586
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:19600
executeDispatch @ react-dom.development.js:30652
processDispatchQueueItemsInOrder @ react-dom.development.js:30684
processDispatchQueue @ react-dom.development.js:30697
dispatchEventsForPlugins @ react-dom.development.js:30708
eval @ react-dom.development.js:30898
batchedUpdates$1 @ react-dom.development.js:23767
batchedUpdates @ react-dom.development.js:27614
dispatchEventForPluginEventSystem @ react-dom.development.js:30897
dispatchEvent @ react-dom.development.js:28670
dispatchDiscreteEvent @ react-dom.development.js:28641

while this is in my vscode terminal:

` ⨯ Detected default export in 'C:\Users\USER\Desktop\myWorks\webdevproj\loginsys\src\app\api\auth\signup\route.ts'. Export a named export for each HTTP method instead.⨯ No HTTP methods exported in 'C:\Users\USER\Desktop\myWorks\webdevproj\loginsys\src\app\api\auth\signup\route.ts'. Export a named export for each HTTP method.
this is my code for my api to POST data  

 import prisma from "@/lib/prisma";
import { NextApiRequest, NextApiResponse } from "next";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    try {
      const { id, name, email, password } = req.body;

      // Check if the user already exists (you may need to customize this logic)
      const existingUser = await prisma.user.findUnique({
        where: { email },
      });

      if (existingUser) {
        return res.status(400).json({ error: 'User already exists' });
      }

      // Create a new user using Prisma
      const newUser = await prisma.user.create({
        data: {
          id,
          name,
          email,
          password, // Note: You should hash the password before saving it to the database
        },
      });

      return res.status(201).json(newUser);
    } catch (error) {
      console.error(error);
      return res.status(500).json({ error: 'Server error' });
    }
  } else {
    return res.status(405).json({ error: 'Method not allowed' });
  }
}

and this is for the frontend part

"use client";

import React, { useState } from "react";

export default function SignUp() {
  const [id, setId] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = async (e: { preventDefault: () => void; }) => {
    e.preventDefault();

    const user = await fetch("/api/auth/signup", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ id, name, email, password }),
    });
  };

  return (
    <form onSubmit={handleSubmit} method="POST">
      <input
        type="text"
        placeholder="username"
        value={id}
        onChange={(e) => setId(e.target.value)}
      />

      <input
        type="text"
        placeholder="name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />

      <input
        type="text"
        placeholder="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />

      <input
        type="password"
        placeholder="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />

      <button type="submit">Sign Up</button>
    </form>
  );
}

I asked chatgpt for assistance with this code though since I am really beginner to webdev frameworks and I am bad at thinking algorithims


Solution

  • You seem to have mistaken app and pages router in Next.js 13. To use client/server components, you need to use app router.

    But your src\app\api\auth\signup\route.ts hanlder is created for the pages router, which will not work with app router. That is why you get the error:

    ` ⨯ Detected default export in 'C:\Users\USER\Desktop\myWorks\webdevproj\loginsys\src\app\api\auth\signup\route.ts'. Export a named export for each HTTP method instead.⨯ No HTTP methods exported in 'C:\Users\USER\Desktop\myWorks\webdevproj\loginsys\src\app\api\auth\signup\route.ts'. Export a named export for each HTTP method.
    

    To fix this error, you need to convert this handler to one compatible with app router, like:

    export async function POST(request: Request) {
        try {
            const { id, name, email, password } = req.body;
    
            // Check if the user already exists (you may need to customize this logic)
            const existingUser = await prisma.user.findUnique({
                where: { email },
            });
    
            if (existingUser) {
                return res.status(400).json({ error: 'User already exists' });
            }
    
            // Create a new user using Prisma
            const newUser = await prisma.user.create({
                data: {
                    id,
                    name,
                    email,
                    password, // Note: You should hash the password before saving it to the database
               },
            });
    
            return res.status(201).json(newUser);
        } catch (error) {
            console.error(error);
            return res.status(500).json({ error: 'Server error' });
        }
    }
    
    

    Refer https://nextjs.org/docs/app/building-your-application/routing/route-handlers for more details.