gpt4 book ai didi

Problem displaying shopping cart items using cookies in a React and Express application(在Reaction and Express应用程序中使用Cookie显示购物车项目时出现问题)

转载 作者:bug小助手 更新时间:2023-10-24 21:37:05 33 4
gpt4 key购买 nike



I have a web application where users can add items to their shopping cart. I use React for the frontend and Express for the backend. When a user adds an item to the basket for the first time, a cookie containing the basket ID is created, valid for 24 hours. The problem I'm experiencing is that items added to the basket are not displayed correctly on the basket page.

我有一个网络应用程序,用户可以添加物品到他们的购物车。我使用Reaction作为前端,使用Express作为后端。当用户第一次向购物篮添加物品时,将创建包含购物篮ID的Cookie,有效期为24小时。我遇到的问题是,添加到购物篮的物品在购物篮页面上显示不正确。


Here's what I've already done:

以下是我已经做过的事情:



  • I configured the Express server to create a cookie with the basket ID when the user adds an item.

  • I set up an Axios request in React to retrieve the cart ID from the cookie.

  • I tried to filter products by cart ID to display them in the cart.


Problem:
The items are not displayed correctly in the shopping cart, even though I use the cart ID to filter the products. I'm sure the cookie is created correctly because I get the cart ID, but something is wrong with the display of the items.
The Cart Component React

问题:即使我使用购物车ID过滤产品,购物车中的商品也不能正确显示。我确信Cookie是正确创建的,因为我得到了购物车ID,但商品的显示有问题。购物车组件作出反应


/** @format */

import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { isEmpty } from "../../Components/Utils";
import TotalPrice from "../../Components/TotalPrice";
import axios from "axios";
import { getCart } from "../../actions/cart.action";
import EmptyCart from "../../Components/EmptyCart";
const Cart = () => {
const cart = useSelector((state) => state.cartReducer);
const products = useSelector((state) => state.productsReducer);
const carts = useSelector((state) => state.cartsReducer);
const dispatch = useDispatch();
console.log(cart);
const [cartId, setCartId] = useState(null);
useEffect(() => {
const fetchCartToken = async () => {
await axios({
method: "get",
url: `${process.env.REACT_APP_API_URL}cartId`,
withCredentials: true,
})
.then((res) => {
setCartId(res.data);
})
.catch((err) => console.log("Le panier est vide!"));
};
fetchCartToken();
if (cartId) dispatch(getCart(cartId));
}, [dispatch, cartId]);
console.log(cartId);

return (
<div>
<header className="header">
<div className="header__topbar">
<Link to="/">
<p className="header__topbar__logo">Panini</p>
</Link>
<div className="header__cart__desktop">
<span className="header__topbar__cart__value"></span>
<Link to="/panier" className="header__topbar__cart__icon">
Mon panier
</Link>
</div>
</div>
<div className="cart__header">
<Link to="/" className="cart__back-icon"></Link>
<h1 className="header__insight">Mon Panier</h1>
</div>
</header>
<main className="main">
<section>
{cart !== null ? (
<>
{" "}
<hgroup className="cart__details">
<h3>Produits</h3>
<h4>Quantités</h4>
<h5>Prix</h5>
<div>#</div>
</hgroup>
<article className="cart__container">
{!isEmpty(products[0]) &&
products.map((product) => {
for (let i = 0; carts.length; i++) {
if (
cart === carts[i].cartId &&
product.id === carts[i].productId
) {
return (
<div key={product.id} className="cart__items">
<div className="cart__items__product">
<div className="cart__items__product__img">
<img
src={product.product_image}
alt="produit ajouter au panier"
/>
</div>
<div className="cart__items__product__infos">
<p>{product.name}</p>
</div>
</div>
<div className="cart__items__quantity">
<div className="cart__items__quantity__container">
<button
className="cart__items__quantity__minus-btn"
id="minus"
>
-
</button>
<span className="cart__items__quantity__product">
{cart.quantity}
</span>
<button
className="cart__items__quantity__plus-btn"
id="plus"
>
+
</button>
</div>
</div>
<div className="cart__items__price__infos">
<p>{product.price}</p>
</div>
<div className="cart__items__delete">
<span className="cart__items__delete__btn"></span>
</div>
</div>
);
}
return null;
}
})}
<TotalPrice cartId={cart} />
<div className="cart__items__next">
<Link to="/contact" className="cart__items__next__btn">
Continuer
</Link>
</div>
</article>
</>
) : (
<EmptyCart />
)}
</section>
</main>
</div>
);
};

export default Cart;

Backend server:js

后端服务器:JS


/** @format */

const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const path = require("path");

//Routes dependences
const adminRoutes = require("./routes/admin.routes");
const categoryRoutes = require("./routes/category.routes");
const productRoutes = require("./routes/product.routes");
const optionRoutes = require("./routes/option.routes");
const cartRoutes = require("./routes/cart.routes");
const orderRoutes = require("./routes/order.routes");

const app = express();

require("dotenv").config("./.env");

//Dependencies server
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
const corsOptions = {
origin: process.env.FRONT_URL,
credentials: true,
allowedHeaders: ["sessionId", "Content-Type"],
exposedHeaders: ["sessionId"],
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
};
app.use(cors(corsOptions));

const { requireAuth, checkCart } = require("./middleware/auth.middleware");

//Get cart cookies
app.get("/cartId", checkCart, (req, res) => {
return res.status(200).json(res.locals.cart.id);
});
//Jwt ROUTES
app.get("/jwtid", requireAuth, (req, res) => {
return res.json(res.locals.admin.id);
});

//Routes
//Admins Routes
app.use("/api/admin", adminRoutes);

app.use("/uploads", express.static(path.join("uploads")));
//Global Routes
app.use("/api/categories", categoryRoutes);
app.use("/api/categories", productRoutes);
app.use("/api/products", productRoutes);
app.use("/api/cart", cartRoutes);
app.use("/api/cart", orderRoutes);

//Strating Server
app.listen(process.env.PORT, () => {
console.log(`Listenning on port ${process.env.PORT}`);
});

Cart action redux

购物车动作重复


/** @format */

import axios from "axios";

export const GET_CART = "GET_CART";

export const getCart = (id) => {
return async (dispatch) => {
return await axios({
method: "get",
url: `${process.env.REACT_APP_API_URL}api/cart/${id}`,
withCredentials: true,
})
.then((res) => {
dispatch({ type: GET_CART, payload: res.data });
})
.catch((err) => console.log(err));
};
};

cart controllers

购物车控制器


const models = require("../models");

const { Product, Option, Cart, OrderItem } = models;

const jwt = require("jsonwebtoken");

const maxAge = 24 * 60 * 60 * 1000; // 24h

const createToken = (id) => {
return jwt.sign({ id }, process.env.CART_TOKEN, {
expiresIn: maxAge,
});
};

//Create a cart
module.exports.addToCart = async (req, res, next) => {
try {
const token = req.cookies.cart;

const { productId, optionId, quantity } = req.body;
const product = await Product.findByPk(productId);

let option;

if (optionId !== undefined) {
option = req.body.optionId;
}
const isFound = await OrderItem.findOne({
where: { productId: product.id },
});

//Check if item has already been added to cart
if (isFound)
return res
.status(401)
.json(`${product.name} a déjà été ajouter au panier`);

if (!token) {
const cart = await Cart.create({});
cart.save();

const sessionToken = createToken(cart.id);
res.cookie("cart", sessionToken, { httpOnly: true, maxAge });
if (cart) {
const createOrder = await OrderItem.create({
CartId: cart.id,
productId,
quantity,
optionId: option,
});
return res
.status(201)
.json({ order: createOrder.toJSON(), sessionToken });
}
} else {
const decoded = jwt.verify(token, process.env.CART_TOKEN);
const cartId = decoded.id;
const cardExisting = await Cart.findByPk(cartId);

if (cardExisting) {
const addOrder = await OrderItem.create({
CartId: cartId,
productId,
quantity,
optionId: option,
});
return res.status(201).json(addOrder.toJSON());
}
}
} catch (error) {
return res.status(500).json(error);
}
};
//Get all cart
module.exports.getCarts = async (req, res) => {
try {
const allCartItems = await OrderItem.findAll({
order: [["createdAt", "DESC"]],
});
return res.send(allCartItems);
} catch (error) {
console.log(error);
return res.status(500).json({ error: "Internal Server Error" });
}
};
//Get cart by cartId
module.exports.getCart = async (req, res) => {
try {
const { id } = req.params;
console.log(id);
const cart = await OrderItem.findOne({ where: { cartId: id } });
console.log(cart);
if (cart.cartId) {
const cartByCartId = await OrderItem.findAll({
where: {
cartId: cart.cartId,
},
order: [["createdAt", "DESC"]],
});
return res.status(200).json(cartByCartId);
} else {
return res.status(404).json("Ce produit n'est pas disponible");
}
} catch (error) {
return res.status(500).json(error);
}
};

Question :

问题:



  1. How can I ensure that items are correctly associated with the server-side basket ID?

  2. Are there any obvious errors in the React code I shared for displaying the cart based on the cart ID?


Any help would be greatly appreciated. Thank you!

任何帮助都将不胜感激。谢谢!


更多回答
优秀答案推荐
更多回答

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com