修补bug
This commit is contained in:
parent
fee075cf87
commit
ae02089dbd
|
@ -5,11 +5,20 @@ import { verifyToken } from "@/lib/auth";
|
|||
|
||||
export async function GET(request) {
|
||||
try {
|
||||
const token = request.headers.get("authorization")?.split(" ")[1];
|
||||
if (!token) {
|
||||
return NextResponse.json([]);
|
||||
}
|
||||
|
||||
const decoded = verifyToken(token);
|
||||
await dbConnect();
|
||||
const cartItems = await Cart.find({}).populate("productId");
|
||||
|
||||
const cartItems = await Cart.find({ userId: decoded.userId }).populate(
|
||||
"productId"
|
||||
);
|
||||
return NextResponse.json(cartItems);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: "获取购物车失败" }, { status: 500 });
|
||||
return NextResponse.json([]);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -13,7 +13,19 @@ export default function Cart() {
|
|||
useEffect(() => {
|
||||
const fetchCartItems = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/cart");
|
||||
const token = localStorage.getItem("token");
|
||||
if (!token) {
|
||||
setCartItems([]);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch("/api/cart", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("获取购物车失败");
|
||||
}
|
||||
|
|
|
@ -1,18 +1,34 @@
|
|||
import React from "react";
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import Product from "@/components/Product";
|
||||
|
||||
async function getProducts() {
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/products`, {
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error("获取商品列表失败");
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
export default function Feed() {
|
||||
const [products, setProducts] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
export default async function Feed() {
|
||||
const products = await getProducts();
|
||||
useEffect(() => {
|
||||
const fetchProducts = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/products");
|
||||
if (!res.ok) {
|
||||
throw new Error("获取商品列表失败");
|
||||
}
|
||||
const data = await res.json();
|
||||
setProducts(data);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchProducts();
|
||||
}, []);
|
||||
|
||||
if (loading) return <div className="p-4">加载中...</div>;
|
||||
if (error) return <div className="p-4 text-red-500">错误: {error}</div>;
|
||||
|
||||
return (
|
||||
<div className="p-4 grid grid-cols-1 gap-4">
|
||||
|
|
Loading…
Reference in New Issue