diff --git a/app/api/cart/route.js b/app/api/cart/route.js index 0a87ccd..f83f3ad 100644 --- a/app/api/cart/route.js +++ b/app/api/cart/route.js @@ -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([]); } } diff --git a/app/tab/cart/page.jsx b/app/tab/cart/page.jsx index 896035d..85d161b 100644 --- a/app/tab/cart/page.jsx +++ b/app/tab/cart/page.jsx @@ -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("获取购物车失败"); } diff --git a/app/tab/page.jsx b/app/tab/page.jsx index 3c7e851..79d7b43 100644 --- a/app/tab/page.jsx +++ b/app/tab/page.jsx @@ -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
加载中...
; + if (error) return
错误: {error}
; return (