项目中遇到的难点

1.发表动态

后端代码:

 async insert (data) {

    let {filename,url} = data;
    // console.log(filename,url,table)
    var base64 = url.replace(/^data:image\/\w+;base64,/, "");//去掉图片base64码前面部分data:image/png;base64
    var dataBuffer = new Buffer.from(base64, 'base64'); //把base64码转成buffer对象,返回一个被 string 的值初始化的新的 Buffer 实例
    var des_file = './public/users/article/' + filename
    console.log(filename);
    //这个方法第一个是文件名,第二个是buffer对象
    fs.writeFile(des_file, dataBuffer, function (err) {//用fs写入文件
        if (err) {
            console.log(err);
        } else {
            console.log('写入成功!');
           return 'ok';
            
        }
    })
   

  }

前端代码:

 update(e) {
    let that = this;
    that.setData({
      text: e.detail.value.text,
      name: e.detail.value.name,
      tel: e.detail.value.tel,
      location: e.detail.value.region + e.detail.value.location
    })
    that.img_upload()
  },
  //图片上传
  img_upload: function () {
    let that = this;
    let imgList = that.data.imgList;
    //由于图片只能一张一张地上传,所以用循环
    for (let i = 0; i < imgList.length; i++) {
      let openid = wx.getStorageSync('openid');
      wx.uploadFile({
        //路径填你上传图片方法的地址
        url: 'http://www.sevenhero.cn:1234/seller/addNewOrder',
        filePath: imgList[i],
        name: 'media',
        formData: ({
          text: that.data.text,
          openid: openid,
          name: that.data.name,
          tel: that.data.tel,
          location: that.data.location
        }),
        success: function (res) {
          wx.hideLoading()
          wx.showModal({
            title: '发布成功',
            showCancel: false,
            success: function (res) {
              wx.switchTab({
                url: '../sale/sale',
              })
            }
          })
          //把上传成功的图片的地址放入数组中        
        },
        fail: function (res) {
          wx.showModal({
            title: '发布失败',
            showCancel: false,

          })
        }
      })
    }
  },

2.登录功能

前端代码

  wx.login({
        success: res => {
          let data = {
            code:res.code,
            username:this.data.userInfo.nickName,
            state:that.data.shenfen
          };
          wx.request({
            url: 'http://www.sevenhero.cn:1234/login',
            method:'POST',
            data:JSON.stringify(data),
            success(res){
              if(res.data){
                wx.setStorage({
                  key:"openid",
                  data:res.data  //这里获取到了openid
                })
              wx.switchTab({
                url: '../sale/sale',
              })
            }
          }
          })
        }
      })

后端代码

async post (c) {
        //发起请求调用小程序服务器api

        let status = JSON.parse(c.body).state,
            username = JSON.parse(c.body).username;

        let login_url = `https://api.weixin.qq.com/sns/jscode2session`
        +   `?appid=${wxkey.appid}`
        +   `&secret=${wxkey.secret}`
        +   `&js_code=${JSON.parse(c.body).code}`
        +   `&grant_type=authorization_code`

        let r;

        await fetch(login_url)
        .then(res=>res.json())
        .then(res=>{
            r = res
        })

        //如果获取openid失败则返回500错误码
        if(r.openid === undefined){
            c.statues = 500
            return
        }

        //检测数据库中是否有此用户
        let myuser = await c.service.model.db_login.findUser(r.openid,status)

        //if this user not exists
        if(myuser == false)
        {
            console.log('没有这个用户,加入此新用户~')
            await c.service.model.db_login.addUser(r.openid,status,username);
        }

        //返回openid
        c.res.body = r.openid;
    }

3.登录和token

首次登录时,后端服务器判断用户账号密码正确之后,根据用户id、用户名、定义好的秘钥、过期时间生成 token ,返回给前端;
前端拿到后端返回的 token ,存储在 localStorage 和 Vuex 里;
前端每次路由跳转,判断 localStorage 有无 token ,没有则跳转到登录页,有则请求获取用户信息,改变登录状态;
每次请求接口,在 Axios 请求头里携带 token;
后端接口判断请求头有无 token,没有或者 token 过期,返回401;
前端得到 401 状态码,重定向到登录页面。
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐