小程序request请求封装

先在utils文件夹下创建http.js文件,在此文件中封装请求

上代码

export default class Http{
  request(url,data=[],method){
    let header = {}
    let token = wx.getStorageSync('token')
    let openid = wx.getStorageSync('openid')
    if(token){
      header.token = token
    }
    if(openid){
      header.openid = openid
    }
	//域名/路由 可以封装起来  这里为了展示没有进行封装
    url = `http://www.xxx.com/${url}`
    return new Promise(function(resolve,reject){
      wx.request({
        url,
        data,
        header,
        method,
		dataType:'json',
        success:(res)=>{
          if(res.statusCode !== 200){
            if(res.data.msg){
              wx.showModal({
                content: res.data.msg,
                showCancel: false
              })
            }else{
              wx.showModal({
                content: '网络连接断开,请稍后重试',
                showCancel: false
              })
            }
            return
          }
          resolve(res.data)
        },
        fail:(ret)=>{
          wx.showModal({
            content: '网络连接断开,请稍后重试',
            showCancel: false
          })
        }
      })
    })
  }
}

页面js调用

import Http from "../../utils/http"

let http = new Http


Page({

  /**
   * 页面的初始数据
   */
  data: {

    slideshow: [],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.getSlideshow();
    
  },

  getSlideshow() {

    //http.request(url,data,method)
    http.request('/api/slideshow').then((res) => {

      this.setData({
        slideshow: res
      })

    })
  }
})

本章还有待完善出,可根据个人情况作出相应调整!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值