购物车 添加购物车数据到数据库

974 阅读2分钟

思路

前端

  1. 点击添加购物车按钮,发送带token 和 商品id 的请求,

后端

  1. 写一个接口,并接收后端传递过来的 商品id 和 token,其中token要进行解析
  2. 根据前端传递过来的token解析后的结果中获取到对应用户,其实就是手机号 进项sql查询对应的用户表进行查询:user,通过查询出用表的tel后,获取到电话所在的数据库id号 作为 用户的uid
  3. 再根据前端传递过来的id,查询商品表 shoplist,把查询出来的相关有效字段, 作为购物车页面表名的字段
  4. 新增一个购物车列表的表cartlist,设计表字段 id ,uid,goods_id,shop_price,shop_title,shop_imgUrl,num
  5. 写一个新增sql语句,将步骤2 和 3查询出来的字段 插入到 新的购物车表中

前端代码:

export default {
  methods: {
    addCard() {
      let id = this.$route.query.id;
      // console.log(id, "123456");
      // 发送请求;
      http
        .$axios({
          method: "POST",
          url: "api/addCard",
          data: { id },
          // 前端发请求带上 headers,参数为token
          headers: {
            token: true,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.success) {
            Toast(res.msg);
          }
        });
    },
  },
};

后端代码:接口:/api/addCard

// 点击加入购物车按钮,接口
router.post('/api/addCard', function (req, res, next) {
  // 前端传递过来的手机号
  let goods_id = req.body.id;
  let tokens = req.headers.token;
  console.log(goods_id, tokens);
  // 解析token
  let tokenObj = jwt.decode(tokens) //结果 { tel: '18666554444', iat: 1628506659 }
  console.log(tokenObj, '123465');

  if (tokenObj == null) {
    res.send({
      data: {
        code: 400,
        success: false,
        msg: '请先登录'
      }
    })
  }

  // 根据解析出来的token,根据tel来获查询用户,查询出来的id作为 用户id
  connection.query(`select * from user where tel ="${tokenObj.tel}"`, function (e, r) {
    console.log(r, '13245646465');
    let uId = r[0].id // 用户uid
    // 根据前端传递过来的商品id 进行数据库查询,查询商品列表
    connection.query(`select * from shoplist where id = ${goods_id}`, function (e, r) {
      // 商品id
      let shopPrice = r[0].price
      let shopTitle = r[0].title
      let shopImgUrl = r[0].imgUrl
      console.log('sss', uId, goods_id, shopPrice, shopTitle, shopImgUrl, 'shoplist40');
      
      // 将数据写入到一个新的购物车列表  写入之前先查一下是否有该商品,如果有就不做插入,把商品数量加+
      connection.query(`select * from cartlist where goods_id = ${goods_id} and uid = ${uId}`, function (e, results) {
        // 如果有,就在原来的数据上 直接加 1 ,没有就执行新增语句
        if (results.length > 0) {
          let num = results[0].num;
          connection.query(`update cartlist set num = ${parseInt(num)+1 } where goods_id = ${goods_id} and uid = ${uId}`, function (err, result) {
            res.send({
              data: {
                code: 200,
                success: true,
                msg: "添加成功!"
              }
            })
          })
        } else {
          connection.query(`insert into cartlist (uid,goods_id,shop_price,shop_title,shop_imgUrl,num) values ("${uId}","${goods_id}","${shopPrice}","${shopTitle}","${shopImgUrl}","1") `, function (err, result) {
            res.send({
              data: {
                code: 200,
                success: true,
                msg: "添加成功!"
              }
            })
          })
        }
      })

    })
  })
})

image.png