Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Next Api Routes data is not sent

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading