Hi guys, I am having problems parsing theb json body, it works if parsed manually but is it possible to parse it automatically?
If I use req.body directly:
The output of req.body is: ReadableStream { locked: false, state: 'readable', supportsBYOB: false }
.
But if I parse it manually it works properly:
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest, res: NextApiResponse
) {
try {
const isStream = typeof req.body === 'object' && req.body?.constructor?.name === 'ReadableStream';
let parsedBody = req.body;
if (isStream) {
const chunks = [];
for await (const chunk of req.body) {
chunks.push(chunk);
}
const rawBody = Buffer.concat(chunks).toString('utf-8');
parsedBody = JSON.parse(rawBody);
}
// Extract stripeId and userId from parsed body
const { stripeId, userId } = parsedBody;
if (!stripeId) {
return res.status(400).json({ error: "stripeId is missing!" });
}
if (!userId) {
return res.status(400).json({ error: "userId is missing!" });
}
return res.status(200).json({
stripeId,
userId,
});
} catch (error) {
console.error("Handler error:", error);
return res.status(500).json({ error: error.toString() });
}
}