I encountered a problem while working on a console project and attempting to create a handler for the GET method in Next.js 14:
TypeError: Cannot destructure property 'q' of 'req.query' as it is undefined.
Below is the code snippet from \api\find\route:
import { PrismaClient } from "@prisma/client";
import { NextApiRequest, NextApiResponse } from "next";
import { useRouter } from "next/router";
import { NextRequest, NextResponse } from "next/server";
const prisma = new PrismaClient();
export async function GET(req: NextApiRequest, res: NextApiResponse) {
const { query } = useRouter();
try {
const { q: query } = req.query;
if (typeof query !== "string") {
throw new Error("Invalid request");
}
const products = await prisma.productCN.findMany({
where: {
title: {
contains: query,
mode: "insensitive",
},
},
});
return NextResponse.json({ products });
} catch (error) {
console.log(error);
return NextResponse.json({ message: error });
}
}