skip to Main Content

I’m trying to test out a contact form in Next.js, it logs the data entered, but not able to send the data to the API, keep getting error

"POST http://localhost:3000/app/(pages)/api/contact/route.tsx 404 (Not Found)"

trying to find out what’s wrong

[the directory setup] (image)(https://phpout.com/wp-content/uploads/2024/01/kz5ch.png)

'use client'

import { useState, FormEvent } from "react"
import React from "react"

export const ContactForm = () => {

    const [name, setName] = useState('')
    const [email, setEmail] = useState('')
    const [message, setMessage] = useState('')
    
    const onSubmit = async (e: FormEvent) => {
        e.preventDefault()
        
    
        try {
            const res = await fetch('/app/(pages)/api/contact/route.tsx',{
                method: 'POST',
                body: JSON.stringify({
                    name, email, message
                }),
                headers: {
                    'content-type': 'application/json'
                }
            })
            if (res.ok) {
                // Handle success
                console.log('Submission successful');
            } else {
                // Handle errors
                console.error('Submission failed');
            }
        } catch (err:any) {
            console.error('Err', err)
        }
    
    }
    
    
    return (
        <main>
            <form 
            className="contact-form"
            onSubmit={onSubmit}>
                <input
                    value={name}
                    onChange={e => setName(e.target.value)}
                    name="name"
                    type="text" 
                    placeholder="NAME"
                    required/>
                <input
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    name="email"
                    type="text" 
                    placeholder="EMAIL"
                    required/>
                <textarea
                    value={message}
                    onChange={e => setMessage(e.target.value)}
                    name="message" 
                    id=""
                    placeholder="MESSAGE"
                />
                <button type="submit">SEND</button>
            </form>
        </main>
    )

}

The contact-form.tsx code

import type { NextApiRequest, NextApiResponse } from "next";

export default function handler(req: NextApiRequest, res: NextApiResponse){

    console.log('Data', req.body)
    
    res.status(200).json({name: "John Doe"})
}

the app/api/contact/route.tsx file code currently

attempted fixes

  1. changed pages directory from "(pages)" to "pages"
  2. copied path directly and copy pasted into fetch

2

Answers


  1. Seems you’re using NextJs 14. Convert the file name from app/api/contact/route.tsx into app/api/contact/route.ts

    Replace the current code of route.ts with this

    import { type NextRequest, NextResponse } from "next/server";
    
    export async function POST(req: NextRequest) {
      const body = await req.json();
    
      return NextResponse.json({ body }, { status: 200 });
    }
    

    See the documentation for more https://nextjs.org/docs/app/api-reference/functions/next-response

    Login or Signup to reply.
  2. When you submit the button and fetch the data never use an extension like ‘route.tsx’

    On the client side

     const res = await fetch('/pages/api/contact',{
                    method: 'POST',
                    body: JSON.stringify({
                        name, email, message
                    }),
    

    On the Api Route Side

    When you make a directory like ‘app/pages/api/contact/route.ts’
    it will detect file ‘/pages/api/contact’

     import {  NextResponse , NextRequest} from "next/server";
     
     export  async function POST(req:NextRequest)  {
     
     const { name,email,message } = await req.json()
     console.log(name,email,message);
     
       return NextResponse.json({mess:message})
     };
    

    The Folder Directory is here

    enter image description here

    I hope it will help you. good luck!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search