微信小程序封装wx.request以及小程序登录

1.封装wx.request

const GET = 'GET';
const POST = 'POST';
const PUT = 'PUT';
const FORM = 'FORM';
const DELETE = 'DELETE';

const baseURL = 'https://alimini.ck9696.com/wxmall';
// const baseURL = 'http://192.168.0.17:8601/wxmall';
var app =  getApp();
function request(method, url, data) {
    return new Promise(function(resolve, reject) {
        var header = {
            'contenst-type': 'application/json',
            'Authorization':wx.getStorageSync('token')
        };
        wx.request({
            url: baseURL + url,
            method: method,
            data: method === POST ? JSON.stringify(data) : data,
            header: header,
            success(res) {
                //请求成功
                //判断状态码---errCode状态根据后端定义来判断
                if (res.data.code == 0) {
                    resolve(res);
                } else if (res.data.code == 501) {
                  // 切换到绑定卡片页面
                  // wx.navigateTo({
                  //   url: '/pages/bindcard/bindcard'
                  // });
                } else {
                    //其他异常
                    reject(res);
                    // console.log(res.data.message)
                    wx.showToast({
                      title: res.data.message,
                      icon: 'none',
                      duration: 2000
                    })
                } 
            },
            fail(err) {
                //请求失败
                console.log(err)
            }
        })
    })
}

 2.用法

const API = {
      getBanner: (data) => request(GET, `/advertising/homeAdvertisingList`),//轮播图
      getGoods: (data) => request(GET, `/product/home?type=${data}`),//热门商品
      addTrolley: (data) => request(POST, `/cart/add`,data),//加入购物车 
}

module.exports = {
  API: API
}

引入

// 获取数据
  async getData() {
    this.setData({
      bannerlist:(await $api.getBanner()).data.data, // 获取轮播
      hotlist:(await $api.getGoods(1)).data.data,    // 热门商品
      morelist:(await $api.getGoods(2)).data.data    // 获取商品列表
    },()=> {
      console.log(this.data);
    })
  },

sure(){
    const that = this
    if(this.data.flog){
      $api.addTrolley(that.data.querydata).then(res => {
        //请求成功
        // console.log(res)
        wx.showToast({
          title: '加入成功',
          icon: 'success',
          duration: 2000,
          success:()=>{
            that.setData({ 
              show: false,
              'querydata.number':1
            });
          }
        })
        $api.getNum().then(res => {
          //请求成功
          that.setData({
            num:res.data.data,
          })
        })
        .catch(err => {
          // console.log("请求失败")
            //请求失败
        })
      })
      .catch(err => {
          //请求失败
      })
    }else{
      var price=that.data.info.price*that.data.querydata.number
      var data={
        allprice:price,
        list:[{
          number:that.data.querydata.number,
          product:that.data.querydata.productId,
          picUrl:that.data.lbimgs[0],
          price:that.data.info.price,
          productName:that.data.info.productName,
        }]
      }
      wx.navigateTo({
        url: '/pages/sureorder/sureorder',
        success: function(res) {
          res.eventChannel.emit('acceptdata', { data: data })
        }
      })
    }
  }

3.小程序登录

   

 wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        const that = this
        wx.request({
          url: 'https://alimini.ck9696.com/wxmall/auth', 
          // url: 'http://192.168.0.111:8601/wxmall/auth', 
          data: {
            code:res.code
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success (res) {
            wx.setStorage({
              key:"token",
              data:res.data.data.token
            })
            that.globalData.iscard = res.data.data.status
          }
        })
      }
    })

     

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值