Whenever I attempt to send a POST request from my frontend within a Next.js project (using TypeScript), the JSON data I expect at my API endpoint does not appear. Instead, all I see is an empty hyperlink that leads nowhere.
The code for my API is placed in the required pages/api/
folder within the project:
import { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const data = req.body;
console.log('from ui', data);
res.status(200).json(data);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
}
On the frontend side:
fetch(`/api/checked-projects`, {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updatedCheckedProjects)
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Failed to post project data.');
}
})
.then((data: any) => {
console.log('Received data:', data);
})
.catch((error) => {
console.error(error);
});
Interestingly enough, console.log('from ui', data);
displays the JSON data:
from ui { data: [ 1, 2, 3, 4 ] }
Even more puzzling is that when I manually insert this data into
res.status(200).json({ data: [1, 2, 3, 4] });
, the information appears correctly at the endpoint.