小程序网络请求工具类

http.js(Promise语法)
import { config } from '../config.js'

var request = function({url, data={}, method="GET"}) {
  return new Promise((resolve, reject)=>{
    goRequest(url, resolve, reject, data, method)
  })
}

var goRequest = function(url, resolve, reject, data = {}, method = "GET") {
  wx.request({
    url: url,
    data: data,
    method: method,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json'
    },
    success: function (res) {
      var code = res.data.code;
      if (code == '1') {
        resolve(res.data)
        console.log(res.data)
      } else {
        reject()
        wx.showToast({
          title: '网络错误',
          duration: 2000
        })
      }
    },
    fail: function (err) {
      reject()
      wx.showToast({
        title: '网络错误',
        duration:2000
      })
    }
  });
}

module.exports = {
  request
}

调用:

    wx.showLoading({
      title: '加载中',
    })
    const h = HTTP.request({
      url: '/miniapp/showCar/getDetailForAppById',
      data: {
        token: getApp().globalData.loginInfo.token,
        id:this.data.bid
      }
    })
    h.then((res) => {
      this.setData({
        carData: res.data,
      })
      wx.hideLoading()
    }, (error) => {
      wx.hideLoading()
    })

推荐阅读更多精彩内容