I'm developing a website for a college class, followed a tutorial on YouTube since I have no real experience with this level of coding. The site "works" locally...when I execute it, at first the screen is just white, but if I refresh the page it comes up, and everything functions (it's a pizza website, the products and ordering and everything works locally). But, when I inspect while the screen is white, I see that I'm getting an internal server error:
I believe the issue is somewhere in my api/products/index file, but I'm not sure
Here is the code for that file:
import dbConnect from "../../../utilities/mongo"
import Product from "../../../models/Product"
export default async function handler(req, res) {
const {method, cookies} = req;
const token = cookies.token
dbConnect()
if(method === "GET"){
try {
const product = await Product.find();
res.status(200).json(product);
} catch (err) {
res.status(500).json(err)
}
}
if(method === "POST"){
if(!token || token !== process.env.TOKEN){
return res.status(401).json("Not Authorized")
}
try{
const product = await Product.create(req.body);
res.status(201).json(product)
}catch(err){
res.status(500).json(err);
}
}
}
Here is a link to my github with all code:
CodePudding user response:
Looking at your repo, I can see you are calling your API endpoint inside your getServerSideProps
function in your index.js
page. You should be writing your DB logic inside getServerSideProps
directly since calling your endpoint in this function is considered inefficient and could give you some problems. You can read more about this here.
Try this:
export const getServerSideProps = async (ctx) => {
const myCookie = ctx.req?.cookies || "";
let admin = false;
if (myCookie.token === process.env.TOKEN) {
admin = true;
}
await dbConnect();
const res = await Product.find();
return {
props: {
pizzaList: JSON.parse(JSON.stringify(res)),
admin,
},
};
};