电商项目实现商品详情页跳转与展示的技术方案咨询
实现商品详情页跳转与数据展示解决方案
问题分析
当前代码存在三个核心问题:
- 商品列表页的View按钮跳转路径未指向正确的详情页路由
- 详情页路由未接收商品ID参数,也未从数据库查询对应商品数据
- 详情页模板错误地使用循环渲染,单个详情页只需展示单条商品数据
分步修改代码
1. 修改index.ejs的跳转链接
将View按钮的href改为带商品ID的完整路由路径:
<% result.forEach(function(product){ %> <div class="product_card col-lg-3"> <img src="images/<%= product.main_img %>"> <div class="product_content"> <p><%= product.product_name %></p> <h5>£<%= product.price %></h5> <!-- 修改href为带ID的详情页路由 --> <a href="/singleproduct/<%= product.id %>" role="button">View</a> </div> </div> <% }) %>
注意:路径中的斜杠使用
/而非\,避免跨平台路径问题
2. 修改app.js的详情页路由
修改路由为带参数的形式,查询数据库中对应ID的商品并传递给模板:
// 假设你已配置好数据库连接实例(如mysql模块的connection) app.get('/singleproduct/:id', function(req, res){ // 获取URL中的商品ID参数 const productId = req.params.id; // 编写SQL查询语句,根据ID查询单个商品 const query = 'SELECT * FROM products WHERE id = ?'; // 执行查询 connection.query(query, [productId], function(error, results){ if(error){ return res.status(500).send('数据库查询错误'); } if(results.length === 0){ return res.status(404).send('商品不存在'); } // 将查询到的单个商品数据传给模板 res.render('singleproduct', { product: results[0] }); }); })
3. 修改singleproduct.ejs模板
去掉循环,直接使用传递过来的单个商品对象渲染:
<div class="single_product_main"> <div class="single_product_imgs"> <img src="images/<%= product.image %>" alt=""> <div class="small_imgs"> <img src="images/<%= product.small_img1 %>" alt=""> <img src="images/<%= product.small_img2 %>" alt=""> <img src="images/<%= product.small_img3 %>" alt=""> </div> </div> <div class="single_product_content"> <h2><%= product.product_name %></h2> <h5>£<%= product.price %></h5> <p><%= product.product_description %></p> </div> </div>
关键说明
- 确保数据库表名(示例中为
products)与你的实际表名一致 - 数据库连接部分需根据项目配置调整(如使用mysql2、Sequelize等工具)
- 错误处理可根据需求优化(比如渲染自定义404页面)
内容的提问来源于stack exchange,提问作者PhilipA1
相关产品推荐
相关产品推荐

