Next.Js fetch를 통해서 request할 때 body 데이터 접근 법
React hook form을 통해서 onValid 된 data를 fetch를 통해서 pages / users / enter.tsx에 요청을 보냈다.
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",
},
});
};이 때 headers에 적힌 "Content-Type" : "application/json"문장이 없으면 enter.tsx에서 req즉 request의 body에 접근했을 때 undefiend가 출력되는 것을 확인할 수 있었는데 이 문제를 해결 하기 위해서는 "Content-Type" : "application/json" 이 옵션이 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
- #접근