I’m using Next.js 13’s api route. I’m sending a string array to the route and I want this to be output as a return value in the response. However all I get I get the error below. In the Chrome debugger I don’t see the array that should actually be sent either. If I change the whole thing to a simple string in the FormData, nothing is sent either
const sendToAPI = () => {
const data = new FormData();
data.append("urls", JSON.stringify(downloadUrls));
fetch("/api/uploadToMongoDB", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => {
console.log(res);
})
.catch((e) => console.log(e));
};
/api/uploadToMongoDB.ts
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
res.status(405).send({ message: 'Only POST requests allowed' })
return
}
const body = await JSON.parse(req.body)
res.status(200).json({ message: `You submitted the following data: ${body}` })
}
error – pages\api\uploadToMongoDB.ts (14:30) @ parse
error – Error [SyntaxError]: Unexpected token o in JSON at position 1
>Solution :
Try to use
body: JSON.stringify({ urls: downloadUrls })
instead of using FormData. FormData isn’t JSON and therefore the conversion cannot be made. If you need to have FormData in your implementation, consider using
body: JSON.stringify(Object.fromEntries(data));
If it still doesn’t work, please let me know!