When I run my Next.Js/MongoDB Project for the first time it always greets me with a "Error: Request failed with status code 500", but after I refresh the page it works totally fine.. Is this going to be a problem when I host my website? and how can I solve it?
import dbConnect from '../../../lib/mongo';
import Item from '../../../models/Item'
export default async function handler(req, res) {
const { method } = req;
dbConnect()
if (method === "GET") {
try {
const items = await Item.find();
res.status(200).json(items);
} catch (err) {
res.status(500).json(err);
}
}
if (method === "POST") {
try {
const item = await Item.create(req.body);
res.status(201).json(item);
} catch (err) {
res.status(500).json(err);
}
}
}
import dbConnect from '../../../lib/mongo'
import Item from '../../../models/Item'
export default async function handler(req, res) {
const { method, query: { id } } = req;
dbConnect()
if (method === "GET") {
try {
const foodItem = await Item.findById(id);
res.status(200).json(foodItem);
} catch (err) {
res.status(500).json(err);
}
}
if (method === "PUT") {
try {
const item = await Item.create(req.body);
res.status(201).json(item);
} catch (err) {
res.status(500).json(err);
}
}
if (method === "DELETE") {
try {
const item = await Item.create(req.body);
res.status(201).json(item);
} catch (err) {
res.status(500).json(err);
}
}
}
Here'es an image showing my Terminal and the Error
1 of 1 unhandled error
This error happened while generating the page. Any console logs will be displayed in the terminal window.
file:///C:/Users/Y520/Desktop/webDevelopment/click-n-eat/node_modules/axios/lib/core/createError.js (16:15)
file:///C:/Users/Y520/Desktop/webDevelopment/click-n-eat/node_modules/axios/lib/core/settle.js (17:12)
file:///C:/Users/Y520/Desktop/webDevelopment/click-n-eat/node_modules/axios/lib/adapters/http.js (322:11)
node:events (538:35)
node:domain (475:12)
node:internal/streams/readable (1345:12)
node:internal/process/task_queues (83:21)
turned out the problem is that I didn't use await before dbConnect
so it should go like:
await dbConnect();
Instead of
dbConnect();