会话有时会返回undefined,但在重新启动页面时会修复

时间:2017-12-17 14:17:04

标签: javascript node.js express session

app.js:

app.use(function(req, res, next) {

// res.locals.ctoken = req.csrfToken();
res.locals.query = req.query;
res.locals.numeral = numeral;
res.locals.moment = moment;

res.locals.messages = req.session.messages;
delete req.session.messages;

//secret message
if (req.session && req.session.secret_message) {
    res.locals.secret_message = req.session.secret_message;
} else {
    res.locals.secret_message = false
}

//admin login
if (req.session && req.session.admin) {
    res.locals.admin = req.session.admin;
}

// products cart
if (req.session && req.session.products) {
    res.locals.products = req.session.products;
} else {
    req.session.products = [];
}

// user login
if (req.session && req.session.user) {
    res.locals.user = req.session.user;
} else {
    res.locals.user = false;
}

next();

});

抛出的错误: enter image description here

视图/分音/ navbar.ejs:

<%

var pricesArray = []

for(var i = 0; i < products.length; i++){
    for(var j = 0; j < cart.length; j++){
        if ( products[i] == cart[j].product_id) {

            var originalPrice = cart[j].product_price
            var discount = cart[j].product_discount
            var afterPrice = originalPrice * ( (100-discount) / 100 )

            pricesArray.push(cart[j].product_discount? afterPrice : cart[j].product_price)

        }
    }
}

var subtotal = pricesArray.reduce((a, b) => a + b, 0);

var cartTotalLength = products.length;

%>

所以基本上,有时候,只要产品会话为空,就会抛出这个错误,当我重新启动页面时,它会消失。我不知道为什么会发生这种情况,我猜测app.js文件中存在问题。我尝试在navbar.ejs文件中执行此操作:

<% if (typeof products == "undefined") products = false %>

但这可能不是最好的解决方案,任何帮助都会受到赞赏。感谢。

0 个答案:

没有答案