Skip to content
Next.Js프로젝트

Next.js: accessing body data when sending a request with fetch

1 min readProjectsMoved from my Tistory blogRead the Korean original

I sent the data validated through onValid in React Hook Form to pages / users / enter.tsx with fetch.

ts
  const onValid = (data: EnterForm) => {
    // console.log(JSON.stringify(data));
    fetch("/api/users/enter", {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json",
      },
    });
  };

I found that without the "Content-Type" : "application/json" line in headers, accessing the body of req, that is, the request, in enter.tsx printed undefined. I learned that to fix this, the "Content-Type" : "application/json" option has to be added to headers.

enter.tsx

ts
import client from "@/libs/client";
import { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  console.log(req.body.email);
  res.status(200).end();
}
  • #data
  • #fetch
  • #Next.js
  • #Request
  • #access

More in Projects