我正在使用 Typescript 和 MongoDB 制作一个电子商务 next.js 应用程序。 这是我当前的文件结构,我将参考:
我的 mainPage.tsx 文件在卡片中呈现我的所有产品。使用 products.map 和 Link,我将每个产品链接到其产品页面,如下所示:
{products.map((product: ProductModel) => (
<Link
key={product._id.toString()}
href={{
pathname: "/product",
query: {
id: `${product._id.toString()}`,
},
}}
>
<CategoryCard product={product} />
</Link>
))}
在我的product/page.tsx 文件中,我从searchParams 获取id,并且我知道到目前为止它工作正常,“console.log("This is the id: ", searchParams.id);”该行正确显示了 id。但这里是取产品
const { product } = await getProduct(searchParams.id);
它在页面上中断并显示“获取产品 id {searchParams.id} 的产品详细信息时出错”。这是文件:
const getProduct = async (id: string) => {
try {
const res = await fetch(
`http://localhost:3000/api/singleproduct?id=${id}`,
{
cache: "no-cache",
}
);
if (!res.ok) {
throw new Error(`Failed to fetch product with id ${id}`);
}
return res.json();
} catch (err) {
console.error("Error fetching product:", err);
throw err;
}
};
const ProductPage = async ({
searchParams,
}: {
searchParams: { id: string };
}) => {
console.log("This is the id: ", searchParams.id);
try {
const { product } = await getProduct(searchParams.id);
return <div>This is a {product.product_title}</div>;
} catch (error) {
console.error("Error fetching product:", error);
return (
<div>Error fetching product details of product id {searchParams.id}</div>
);
}
};
export default ProductPage;
现在这是问题可能源自的 api/singleproduct/route.tsx 文件。这是代码:
import Product from "../../models/Product";
import { NextResponse } from "next/server";
import { NextApiRequest, NextApiResponse } from "next";
export async function GET(req: NextApiRequest, res: NextApiResponse) {
console.log("Query parameters:", req.query);
const id = req.query.id as string;
console.log("this is the id:", id);
try {
if (!id) {
throw new Error("ID parameter is missing.");
}
console.log("This is the id:", id);
const product = await Product.findById(id);
if (!product) {
return NextResponse.json({ error: "Product not found" }, { status: 404 });
}
console.log("Product from MongoDB:", product);
return NextResponse.json({ product }, { status: 200 });
} catch (error) {
console.log("Something broke:", error);
return NextResponse.json({ message: "GET request failed.", error });
}
}
我在控制台中收到“查询参数:未定义”和错误“TypeError:无法读取未定义的属性(读取“id”)”。我怎样才能解决这个问题?谢谢一百万。
req.query 对象未定义,这意味着路由未正确接收查询参数。在 Next.js API 路由文件 api/singleproduct/route.tsx 中,您尝试使用 req.query.id 访问查询参数。但是,对于通过 GET 请求传入的查询参数,您应该直接使用 req.query 访问它们,而不是将其与 id 链接。尝试这样的方法,看看是否可以解决问题,
... all imports...
export async function GET(req: NextApiRequest, res: NextApiResponse) {
try {
const id = req.query.id as string;
if (!id) {
throw new Error("ID parameter is missing.");
}
console.log("This is the id:", id);
const product = await Product.findById(id);
if (!product) {
return NextResponse.json({ error: "Product not found" }, { status: 404 });
}
console.log("Product from MongoDB:", product);
return NextResponse.json({ product }, { status: 200 });
} catch (error) {
console.log("Something broke:", error);
return NextResponse.json({ message: "GET request failed.", error });
}
}
确保您的 API 路由配置正确,并且前端的请求正确发送 id 参数。如果您仍然遇到问题,请仔细检查您发出请求的前端代码,以确保正确发送 id 参数。