添加到购物车nodejs mysql ejs

问题描述 投票:1回答:1

我想将产品添加到我的购物车,我在差异页面上使用了不同的路线。因此,在我的app.js文件中,我具有网页所需的路由,但是我无法获取ID以显示在我的ejs视图中。有人可以帮忙吗?下面是我的代码。我认为问题是我单击添加到购物车按钮

时ID不显示
<!DOCTYPE html>
<html lang="en">

<head>
    <% include partials/head %>
</head>

<body>
    <% include partials/menu %>

    <!--Product Cards-->
    <div class="container">
        <!-- Traverse through Database data-->
        <% productsData.forEach(function(result) { %>
        <div class="card">
            <div class="imgBx">
                <img src="<%= result.imagePath %>" alt="">
            </div>
            <div class="contentBox">
                <h2><%= result.prod_title %></h2>
                <h3>$<%= result.price %></h3>
                <div class="size">
                    <h3>Size :</h3>
                    <span><%= result.size %></span>

                </div>
                <a class="add-cart" href="/addToCart/<%= this.id %>">ADD TO CART</a>
            </div>
        </div>
        <% }); %>

    </div>
</body>
<% include partials/script %>

</html>



router.get('/', function (req, res){
    var productId = req.params.id;
    var cart = new Cart(req.session.cart ? req.session.cart : {items: {}} );

    var sql = 'SELECT prod_id FROM product';
    databaseConnection.query(sql, function(err, results, fields) {
        if (err){
            throw err;
        } else {
            cart.add(results, results.id);
            req.session.cart = cart;
            console.log(req.session.cart);
            res.redirect('/shop');

        }
    });
});





// Import Routes 
var homeRouter = require('./routes/home');
var signInRouter = require('./routes/signIn');
var shopRouter = require('./routes/shop');
var registerRouter = require('./routes/register');
var signOutRouter = require('./routes/signOut');
var cartRouter = require('./routes/addToCart');

// Use Routes
app.use('/', homeRouter);
app.use('/signIn', signInRouter);
app.use('/shop', shopRouter);
app.use('/register', registerRouter);
app.use('/signOut', signOutRouter);
app.use('/addToCart/:id', cartRouter);
mysql node.js ejs
1个回答
0
投票

如果您在此处使用result变量:

<h2><%= result.prod_title %></h2>
<h3>$<%= result.price %></h3>

我只假设您应该使用它在此处生成添加到购物车的链接:

href="/addToCart/<%= result.id %>"

关于您所拥有的:

href="/addToCart/<%= this.id %>"

但是,如果您在与定义路由器不同的位置设置path参数,则需要使用var router = express.Router({ mergeParams: true });作为指定的here

© www.soinside.com 2019 - 2024. All rights reserved.