微信小程序封装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
          }
        })
      }
    })

     

你可能感兴趣的:(微信小程序,小程序)