HTTP请求方法的封装

HTTP请求方法的封装

在小程序中http请求是很频繁的,但每次都打出wx.request是很烦的,而且代码也是冗余的,所以我们要把他封装起来
首先要在utils文件夹中新建一个js,我命名为request.js,在里面封装出post和get的请求,记得最后要声明出来

//封装请求
const app = getApp()
let host = app.globalData.url

/**
 * POST 请求
 * model:{
 *  url:接口
 *  postData:参数  {}
 *  doSuccess:成功的回调
 *   doFail:失败回调
 * }
 */
function postRequest(model) {
  wx.request({
    url: host + model.url,
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    method: "POST",
    data: model.data,
    success: (res) => {
      model.success(res.data)
    },
    fail: (res) => {
      model.fail(res.data)
    }
  })
}

/**
 * GET 请求
 * model:{
 *   url:接口
 *   getData:参数 {}
 *   doSuccess:成功的回调
 *   doFail:失败回调
 * }
 */
function getRequest(model) {
  wx.request({
    url: host + model.url,
    data: model.data,
    success: (res) => {
      model.success(res.data)
    },
    fail: (res) => {
      model.fail(res.data)
    }
  })
}

/**
 * module.exports用来导出代码
 * js中通过 let call = require("../util/request.js")  加载
 */
module.exports = {
  postRequest: postRequest,
  getRequest: getRequest
}

module.exports = {
postRequest: postRequest,
getRequest: getRequest
}

使用时就在相应的页面顶部调用,Page外部噢

let call = require("../../utils/request.js")

使用的时候↓

get
//获取广告图
    call.getRequest({
      url:'GetAd',
      success:(res)=>{      //箭头函数没有指针问题
        this.setData({
          urlItem: res.data
        })
      }
    })
post
call.postRequest({
      url: 'addorder',
      data: {
        shop_id: that.data.shop_id,
        user_id: app.globalData.user_id,
        coupon_sn: that.data.coupon_sn,
        carType: that.data.car_type,
        appointtime: that.data.toTime
      },
      success:(res)=>{
        console.log(res)
        wx.navigateTo({
          url: '../selectPay/selectPay?order_sn=' + res.data.order_sn + '&fee=' + res.data.real_pay + "&order_id=" + res.data.order_id,
        })
      }
    })

猜你喜欢

转载自blog.csdn.net/m0_46621937/article/details/106516350