When I’m trying to make a POST request from my frontend side in Next.js project (with TypeScript), my API endpoint doesn’t show desired JSON data, but only empty hyperlink string leading to nowhere.endpoint
my code for API is located as needed in pages/api/
folder inside 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' });
}
}
Frontend part:
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);
});
However, console.log('from ui', data);
prints json data:
from ui { data: [ 1, 2, 3, 4 ] }
Even more strange is that when I put this data as hardcoded into res.status(200).json({ data: [1, 2, 3, 4] });
, the data is shown in endpoint alright.
Yulo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.