token: 过期时间处理:有瑕疵,问题到时候懂了 再解决吧(老师讲课也很恶心,越到后面越不像样,抽个烟都要录在视频里告诉你,那一边讲课一边抽烟就错漏百出)

167 阅读2分钟

token 过期时间.png

后端

一 index.js 判断超过 60秒的时间函数

// 处理token过期时间 60s
function getTokenTime(exp) {
  let getTimes = parseInt(new Date().getTime() / 1000) // 获取当前时间戳 并转为秒
  if ((getTimes - exp) > 60) {
    console.log(getTimes - exp, getTimes, exp);
    return true
  }
}

二 在加入购物车接口的时候用了一下getTokenTime 这个函数,并跟 更新数据库的 token

 // 点击加入购物车按钮,接口
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 }
  // 如果调用了这个方法 返回true,证明token过期,
  if (getTokenTime(tokenObj.exp)) {
    console.log(tokenObj.exp, "2 tokenObj.exptokenObj.exptokenObj.exp");
    res.send({
      data: {
        code: 1000,
        msg: "token已过期"
      }
    })
  } else {
    // 根据解析出来的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: "添加成功!"
                }
              })
            })
          }
        })

      })
    })
  }
})

三 userQuery.js 设置token有效时间 60秒

// 插入手机号和密码
insertTel(option) {
let tel = option.tel || "新增手机号"
let pwd = option.pwd || "999999"
// token相关
let jwt = require('jsonwebtoken'); //   引入 token 包
let payload = {
    tel: tel
} // 用户信息
let secret = "mixuebingcheng"; // 口令
let token = jwt.sign(payload, secret, {
    expiresIn: 60 // token 有效时间 60s
}) // 生成token: 

return `insert into user (tel,pwd,imgUrl,name,token) values ("${tel}","${pwd}","../images/lvcha.jpeg","${tel}","${token}")`
}

四 在login 的 用户名密码登录 使用了登录的情况

// 用户登录接口 账号密码登录
router.post('/api/login', function (req, res, next) {
  // 接收前端过来的数据
  let params = {
    tel: req.body.tel,
    pwd: req.body.pwd
  }

  // token相关
  let jwt = require('jsonwebtoken'); //   引入 token 包
  let payload = {
    tel: params.tel
  } // 用户信息
  let secret = "mixuebingcheng"; // 口令
  let token = jwt.sign(payload, secret, {
    expiresIn: 60 // token 有效时间 60s
  }) // 生成token: 

  // 查询手机号
  connection.query(user.queuryTel(params), function (err, result) {
    if (result.length > 0) {
      // 记录id
      let id = result[0].id
      console.log(id, "ididi222222222222222");
      // 手机号存在,判断密码
      connection.query(user.queuryPwd(params), function (err, result) {
        if (result.length > 0) {
          // 将旧的token 替换新的token
          connection.query(`update user set token = "${token}" where id = ${id}`, function (e, r) {
          })
          res.send({
            code: 200,
            data: {
              success: true,
              msg: '登录成功,已更新token',
              data: result[0]
            }
          })
        } else {
          // 密码不对
          res.send({
            code: 302,
            data: {
              success: false,
              msg: '密码错误'
            }
          })
        }
      })
    } else {
      //  手机号不存在
      res.send({
        code: 301,
        data: {
          success: false,
          msg: '手机号不存在'
        }
      })
    }
  })
})

前端 common api request.js

return axios(ocptions).then(v => {
    let data = v.data.data
    console.log(data, "data");
    // 判断后端返回的token过期code吗 是否为 1000 如果是 就跳转到登录页
    if (data.code == '1000') {
        Indicator.close();
        router.push('/login');
        localStorage.removeItem('userData')
    }

    return new Promise((res, rej) => {
        if (!v) return rej();
        // 关闭loading
        setTimeout(() => {
            Indicator.close();
        }, 300);
        res(data)
    });
    })