微信小程序封装接口

1 baseurl.js

module.exports = {
  // 开发环境
basePath:'https://www.easy-mock.com/mock/5d257e0a77744b2808b88407/study'

// 测试环境
// basePath: 'https://www.easyLmock.com/mock/5d257e0a77744b2808b88407/study'

//   // 正式环境
// basePath: 'https://www.easy-mock.com/mock/5d257e0a77744b2808b88407/study'

}

2 api.js

const base = require('./baseurl.js')
const url = base.basePath
module.exports = {
  goodsList: url + '/miniHotgoods',
  cityList: url+'/cityList',
  richText:url+'/richText',
  jiaju: url +'/jiaju',
  AllList:url + '/list'
}

3 request.js

module.exports = {
  _get:function(url,data){
    var promise = new Promise((resolve,reject)=>{
      let param = data;//接受传来的参数data
      wx.request({
        url: url,
        // header:{}
        data:param,
        method:'get',
        success:function(res){
          console.log(res)
          if(res.statusCode == 200){
            resolve(res)
          }else{
            reject(res.errMsg)
          }
          
        },
        error:function(e){
          reject('网络错误')
        }
      })
    })
    return promise
  },

  _post: function (url, data) {
    var promise = new Promise((resolve, reject) => {
      let param = data;//接受传来的参数data
      wx.request({
        url: url,
        // header: { "Content-type":'application/x-www-form-urlencoded'},
        data: param,
        method: 'post',
        success: function (res) {
          console.log(res)
          if (res.statusCode == 200) {
            resolve(res)
          } else {
            reject(res.errMsg)
          }

        },
        error: function (e) {
          reject('网络错误')
        }
      })
    })
    return promise
  }

}

4使用

const request = require('../../assets/js/request.js')
const api = require('../../assets/js/api.js')

// 请求城市数据

  getCity: function() {
    let that = this
    request._get(api.cityList).then((res) => {
      console.log(res)
      //定义全局变量cityList 存储城市数据
      cityList = res.data
      let arr = []
      res.data.forEach((item) => {
        arr.push(item.name)
      })
      that.setData({
        province: arr
      })
// 设置默认选中省份
      that.initChooseCity()
    })
  },

你可能感兴趣的:(微信小程序封装接口)