gpt4 book ai didi

javascript - 将数据购物车存储到 cookie 中需要很大的空间

转载 作者:行者123 更新时间:2023-12-03 00:24:50 24 4
gpt4 key购买 nike

我在将数据输入 cookie 时遇到问题。

数据是一个数组,其尺寸很大,例如product_id、name等等。

但我看到一些电子商务网站的添加到购物车数据功能没有直接存储到cookie中,而只是设置它,因为当我删除cookie时,数据会丢失,但当添加新数据时,内存cookie并没有增加。

所以我的问题是数据存储在哪里?因为我检查过它即使在本地存储中也是空的

我所做的是这样的:我使用数据数组将数据输入到 cookie 中,并将其更改为 JSON.stringify。在本例中,我只放了 2 个数据,结果大小为 2539,这意味着它太大了。

Data cart in cookies

我的 Controller 添加到购物车

import db from '../../config/conn';

export const addToCart = (req,res) =>{
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate() + 1);
let reqBody = JSON.stringify(req.body);
let cart = [];
if(typeof req.cookies.cart == "undefined"){
cart.push(reqBody);
}else{
cart = JSON.parse(req.cookies.cart);
cart.push(reqBody);
}

cart = JSON.stringify(cart);
res.cookie('cart', cart, { maxAge: 24 * 60 * 60 * 1000, expired: tomorrow})
return res.status(200).json(cart);
}

服务器

import express from 'express';
import bodyParser from 'body-parser';
// import passport from 'passport';
import connection from './config/conn';
import { CategoryRoutes,ProductRoutes,CartRoutes} from './modules';
import session from 'express-session';
import csrf from 'csurf'
import cors from 'cors'
import cookieParser from 'cookie-parser'
const app = express();
app.use(cookieParser());
app.use(session({
secret: 'iCtkGVe0-4FKIGgBopL2QUM9K-jIK9miZhQE',
resave: false,
saveUninitialized: true,
cookie: {
secure: true,
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000
}
}));

app.use(csrf({ cookie: true }));

app.use((req,res,next)=>{
res.header('X-XSS-Protection', '1; mode=block');
res.header('X-Frame-Options','deny');
res.header('X-Content-Type-Options','nosniff');
res.removeHeader("X-Powered-By");
res.cookie('c_token', req.csrfToken());
next();
})
app.use(cors({ origin:'http://localhost:3000/',credentials:true}))

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api/', [CategoryRoutes, ProductRoutes, CartRoutes]);

const port = process.env.PORT || 5000;
app.listen(port, (err) => {
if(err){
console.log(err);
}else{
console.log(`Server running on port ! ${port}`);
}

});

What should I do?how to create Cart system in the right way ?

最佳答案

how to create Cart system in the right way ?

尽管听起来很俗气,但在编程中并没有“正确的方法”来做很多事情。就我个人而言,我倾向于将购物车信息存储在本地存储中,这对于我的情况来说效果很好。将其存储在 cookie 中是可能的,但会产生负面影响,即该 cookie 将随每个请求一起发送,即使对于图像或 api 调用也是如此(假设您的 api 在同一域上运行)。

so my question is where is the data stored?

许多网站不会将其存储在本地存储中,或本地计算机上的任何位置。他们将其存储在服务器上,当您打开页面时,他们会检索它。 Cookie 主要只存储用于从 api 获取购物车商品的身份验证 token 。想象一下,有一个像 http://mywebshop.com/api/cart_items 这样的端点,它返回项目列表。

这种方法在本地存储中存储所没有的优点是,当您移动到另一台计算机(但使用相同的登录名)时,您的购物车仍然存在。另外,在高级场景中,我可以想象当从网站上删除该商品时,想要从所有包含该商品的购物车中删除该商品。

关于javascript - 将数据购物车存储到 cookie 中需要很大的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54134071/

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