I'm experimenting with nextjs+react and can't figure out something extremely trivial - sending and receiving a post request via the internal API: The stringified JSON is not recognized and thus not parsed correctly.
Client component
const data1 = { key: 'test123' };
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(data1),
});
API page (/pages/api/chat.tsx)
export default async function handler(req: NextApiRequest,
res: NextApiResponse): Promise<any> {
const data = JSON.parse(req.body)
console.log(data)
}
Error
The console prints the error:
pages/api/chat.tsx (10:22) @ parse ⨯ SyntaxError: "[object Object]" is not valid JSON
at JSON.parse (<anonymous>)
at handler (webpack-internal:///(api)/./pages/api/chat.tsx:6:23)
From what I've read, nextjs should understand the body as json because it is set in the headers of the request. However, this does not work.
Where am I wrong?
Next.js automatically parses the
Content-Typeof thebodyparameter. See the docs here.In your case, simply remove the usage of
JSON.parsein your api route, e.g.: