无法阅读财产" totalQty'未定义的

时间:2018-05-29 06:34:02

标签: javascript node.js express ejs

我创建了一个购物车对象,可以将商品存储在购物车中。问题是在将物品放入购物车之前未定义。即使在会话期间没有任何内容,我如何定义购物车?我使用的是ejs。

这是我的错误

/home/ubuntu/workspace/views/partials/header.ejs:37
    35|                 </li>
    36|                 <li>
 >> 37|                   <a href="cart" class="navport"><span 
class="badge"><%= session.cart.totalQty || 0%></span></a>
    38|                 </li>
    39|               </ul>
    40|               

Cannot read property 'totalQty' of undefined

App.js

var express = require("express");
var app = express();
var mongoose = require("mongoose"),
    User = require("./models/user"),
    bodyParser = require("body-parser"),
    ejs         = require("ejs"),
    passport = require("passport"),
    LocalStrategy = require("passport-local"),
    localMongoose = require("passport-local-mongoose"),
    session = require("express-session"), 
    MongoStore = require("connect-mongo")(session),
    Cart = require("./models/cart"),
    Clothes = require("./models/clothes");
mongoose.connect("mongodb://localhost/bitchinvintage");
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));


app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
    secret: "random dogga",
    resave: false,
    saveUninitialized: false,
    store: new MongoStore({mongooseConnection: mongoose.connection}),
    cookie: {maxAge: 180 * 60 * 1000}
}));
app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function (req, res, next) {
  res.locals.login = req.isAuthenticated();
  res.locals.session = req.session;
  next();
});
app.get("/", function(req, res){
    res.render("landing");
});
// Clothes Routes
app.get("/clothes", function(req, res){
    // Get all campgrounds from DB
    Clothes.find({}, function(err, clothes){
       if(err){
           console.log(err);
       } else {
          res.render("clothes",{clothes:clothes});
       }
    });
});
app.get("/clothes/new", function(req, res){
    res.render("new");
});

app.post("/clothes", function(req, res){
    var name = req.body.name;
    var overlay = req.body.overlay;
    var price = req.body.price;
    var image = req.body.image;
    var newClothes = {name: name, image: image, price: price, overlay: overlay}
    Clothes.create(newClothes, function(err, newlyCreated){
        if(err){
            console.log(err);
        } else{
            res.redirect("/clothes");
        }
    });
});
// ------------------


// Register Routes
app.get("/register", function(req, res){
    res.render("register");
});
app.post("/register", function(req, res){
    var newUser = new User({username: req.body.username});
    User.register(newUser, req.body.password, function(err, user){
        if (err){
            console.log(err);
            return res.render("register");
        }
        passport.authenticate("local")(req, res, function(){
            res.redirect("/");
        })
    })
});
// -----------

// Login Routes
app.post("/login", passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/register"
}), function(req, req){

});

// Cart Routes
app.get("/add-to-cart/:id", function(req, res, next){
    var productId = req.params.id;
    var cart = new Cart(req.session.cart ? req.session.cart : {});
    console.log("works");
    Clothes.findById(productId, function(err, clothes){
        if(err){
            return res.redirect("/");
        }
        cart.add(clothes, productId);
        req.session.cart = cart;
        console.log(req.session.cart);
        res.redirect("/clothes");
    });
});
// ------------
app.get("/account", isLoggedIn, function(req, res){
});
app.get("/*", function(req, res){
    res.render("error");
});

app.listen(process.env.PORT, process.env.IP, function(){
    console.log("Vintage server Starting...")
});

function isLoggedIn(req, res, next) {
    if (req.user) {
        next();
    } else {
       res.redirect("/account"); 
    }
}    

模型/ cart.js

这是购物车对象

module.exports = function Cart(oldCart) {
    this.items = oldCart.items || {};
    this.totalQty = oldCart.totalQty || 0;
    this.totalPrice = oldCart.totalPrice || 0;


    this.add = function(item, id) {
        var storedItem = this.items[id];
        if (!storedItem){
            storedItem = this.items[id] = {item: item, qty: 0, price: 0}
        }
        storedItem.qty++;
        storedItem.price = storedItem.item.price * storedItem.qty;
        this.totalQty++;
        this.totalPrice += storedItem.price;
    }
    this.generateArray = function() {
        var arr = [];
        for (var id in this.items) {
            arr.push(this.items[id]);

        }
        return arr;
    }
};

header.ejs

这是HTML,我试图在导航栏中列出购物车中的总金额

<li>
<a href="cart" class="navport"><span class="badge"><%= 
session.cart.totalQty || 0%></span></a>
</li>
</ul>

2 个答案:

答案 0 :(得分:0)

 var Cart = require('../models/cart');   

(购物车模型的路径) 你在路线中加入了这条线吗?因为你得到购物车它是未定义的错误。请确保您已在路线文件中包含上述行。当您创建购物车对象时,此行将帮助您参考购物车模型。

答案 1 :(得分:0)

在加载索引模板时,我遇到了同样的问题。您可以在渲染购物车数量之前检查session.cart是否可用吗?我添加了以下简单的if条件,它对我有用。

<% if(session.cart) { %>
    <span class="badge"><%= session.cart.totalQty %></span>
<% } %>