You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

电商项目中点击查看按钮实现商品详情页展示的技术咨询

实现商品详情页跳转功能的步骤

1. 修正首页View按钮的跳转链接

你的index.ejs里,View按钮的href仅填写商品ID会导致跳转路径错误,需修改为带路由前缀的格式,确保请求能正确指向详情页路由:

<div class="row">
    <% 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为带路由的完整地址 -->
            <a href="/singleproduct/<%= product.id %>" role="button">View</a>
        </div>
    </div>
    <% }) %>
</div>

2. 修改后端路由,获取商品ID并查询数据库

app.js里的路由需要接收商品ID参数,通过ID从MySQL查询对应商品数据,再将数据传递给详情页渲染。假设你已配置好MySQL连接(如使用mysql2模块),修改路由如下:

// 假设已初始化MySQL连接(示例):
// const mysql = require('mysql2');
// const connection = mysql.createConnection({
//   host: 'localhost',
//   user: '你的用户名',
//   password: '你的密码',
//   database: '你的电商数据库名'
// });

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(err, results){
        if(err){
            return res.status(500).send('数据库查询失败');
        }
        if(results.length === 0){
            return res.status(404).send('该商品不存在');
        }
        // 将查询到的单个商品数据传给详情页模板
        res.render('singleproduct', { product: results[0] });
    })
})

3. 修正商品详情页的渲染逻辑

singleproduct.ejs原本用forEach循环处理数据,但我们仅需渲染单个商品,因此去掉循环,直接使用传入的product对象:

<div class="single_product_main">
    <div class="single_product_imgs">
        <img src="images/<%= product.image %>" alt="<%= product.product_name %>"> <!-- 补充alt文本提升可访问性 -->
        <div class="small_imgs">
            <img src="images/<%= product.small_img1 %>" alt="<%= product.product_name %>">  
            <img src="images/<%= product.small_img2 %>" alt="<%= product.product_name %>">  
            <img src="images/<%= product.small_img3 %>" alt="<%= product.product_name %>"> 
        </div>
    </div>
    <div class="single_product_content"> 
        <h2><%= product.product_name %></h2> 
        <h5>£<%= product.price %></h5> 
        <p><%= product.product_description %></p> 
    </div>
</div>

额外提示

  • 确保数据库表名(示例中为products)、字段名与你的实际数据库结构一致;
  • 处理数据库查询错误和商品不存在的场景,避免页面崩溃;
  • 图片路径统一使用斜杠/,适配不同操作系统的路径解析规则。

内容的提问来源于stack exchange,提问作者PhilipA1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 20:09:50