我正在使用parse.com动态网站来构建产品网站。我想使用会话cookie将一些数据存储在bowser会话cookie中。这是我的app.js
var express = require('express');
var parseExpressHttpsRedirect = require('parse-express-https-redirect');
var parseExpressCookieSession = require('parse-express-cookie-session');
var app = express();
// Global app configuration section
app.set('views', 'cloud/views');
app.set('view engine', 'ejs');
app.use(parseExpressHttpsRedirect());
app.use(express.bodyParser());
app.use(express.cookieParser('YOUR_SIGNING_SECRET'));
app.use(parseExpressCookieSession({
cookie : {
maxAge : 3600000
}
}));
app.use(express.cookieSession());
app.use(app.router);
我在app.js中有这个方法,它应该返回购物车中添加的项目
function getProductsInCart(req) {
var productsInCart = req.session.productsInCart;
if(!productsInCart) {
return [];
}
return productsInCart;
}
这是在购物车中添加新产品的方法
app.get('/add-cart/*', function(req, res) {
var url = req.url;
var productId = url.split('/')[2];
var productsInCart = getProductsInCart(req);
productsInCart.push(productId)
req.session.productsInCart = productsInCart;
console.log("productsInCart: " + JSON.stringify(productsInCart));
});
我面临的问题是getProductsInCart方法总是返回一个空数组,这意味着会话没有将对象存储在cookie中。这应该很简单,我不明白为什么它不起作用。任何指针都会深受赞赏。
答案 0 :(得分:0)
我做错了两件事
这是有效的代码
app.get('/add-cart/*', function(req, res) {
var url = req.url;
var productId = url.split('/')[2];
var productsInCart = getProductsInCart(req);
console.log("productsInCart: " + JSON.stringify(productsInCart));
productsInCart.push(productId);
res.cookie('productsInCart', productsInCart, {
signed: false,
expires: new Date(Date.now() + 1000000)
});
res.send(req.cookies);
});
function getProductsInCart(req) {
var productsInCart = req.cookies.productsInCart;
if(!productsInCart) {
return [];
}
return productsInCart;
}