how do I send data from my client component to my server side POST route Handler with Next.js app router

24 views Asked by At

I keep getting undefined when I try to destructure the body object from my const { title, body, userId } = request.body;

I have 2 components, a server that post data to an API endpoint and a client component that reads the server component locally and is supposed to send the body data collected from inputs to the server content. am not getting any error aside from undefined. here is the server component:

import { NextResponse } from "next/server"

export async function GET() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts')
    const data = await res.json()
//    console.log({ data })
const post = data.slice(0,5)

    return Response.json({ data:post })
  }


  export async function POST(request, response) {
   
    const { title, body, userId } = request.body;
    console.log({ title, body, userId })
    const fetchResponse = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: {
        'Content-type': 'application/json; charset=UTF-8',
      },
      body: JSON.stringify({
        title,
        body,
        userId,
      })
      
    });
  
    const data = await fetchResponse.json();
    console.log(data)
    return NextResponse.json(data); 
  }

and here is the client component:

"use client"

import { useState } from "react";


const Postapost = () => {
const [title, settitle] = useState("")
const [body, setbody] = useState("")


console.log(title)
console.log(body)

const Handlepost = async () => {
  const userId = 1;
  const fullpost = {
    title,
    body,
    userId,
  };

  const response = await fetch('http://localhost:3000/api', { 
    method: 'POST',
    headers: {
      'Content-type': 'application/json; charset=UTF-8',
    },
    body: JSON.stringify({title, body, userId}),
   
  },
  console.log(fullpost)
  )

  .then((response) => response.json())
  .then((json) => console.log(json));
};

    return ( <div>
<input type="text" name="title" onChange={(e) => {settitle(e.target.value)}} />
<input type="text" name="body" onChange={(e) => {setbody(e.target.value)}} />
<button onClick={Handlepost}>add post</button>
    </div> );
}
 
export default Postapost;
0

There are 0 answers