Here is the code snippet for my GET request in the API section:
export default async (req, res) => {
const { query: { className }, method } = req;
switch (method) {
case "GET":
try {
const classDetail = await Class.findOne({title: className});
if (!classDetail) {
return res.status(400).json({ success: false });
}
res.status(200).json({ success: true, data: classDetail });
} catch (error) {
res.status(400).json({ success: false });
console.log(error);
}
break;
default:
res.status(400).json({ success: false });
}
On my [className] page, I am attempting to retrieve data from the following API endpoint:
http://localhost:3000/api/admin/classes/${className}
. However, when I log the response, it shows as undefined.
export async function getServerSideProps({ query: { className } }) {
const res = await fetch(`http://localhost:3000/api/admin/classes/${className}`)
.then(() => console.log(`first get request sent: `));
// const { data } = await res.json();
console.log(res)
return { props: { classDetail: 1 } };
}
Interestingly, when I make the same GET request using Postman with the endpoint
http://localhost:3000/api/admin/classes/class-3
, it returns the expected data. Why am I not receiving the same data within getServerSideProps?
{
"success": true,
"data": {
"_id": "62f6858ea26fbb47b3cc0563",
"title": "class-3",
"classImageURL": "http://res.cloudinary.com/nhnasem/image/upload/v1660323222/HELP_ME_ewcr5t.png",
"imageWidth": "1555",
"imageHeight": "2000",
"__v": 0
}
}
What could be causing this issue and how can I resolve it?
Edit: I also tested it with the JSONPlaceholder API, but encountered the same 'undefined' result.
Edit 2: Handling requests for two APIs
export async function getServerSideProps({ query: { className } }) {
const res = await fetch(
`http://localhost:3000/api/admin/classes/${className}`
);
const {data} = res.json()
const res2 = await fetch(
`http://localhost:3000/api/admin/classes/${className}/subjects`
);
const {data} = await res2.json() // this won't work as it was already called and declared before
return { props: { classDetail: data, subjects: data} };
}