美文网首页
小程序网络请求工具类

小程序网络请求工具类

作者: 马戏团小丑 | 来源:发表于2018-11-27 16:29 被阅读9次
    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()
        })
    

    相关文章

      网友评论

          本文标题:小程序网络请求工具类

          本文链接:https://www.haomeiwen.com/subject/hbzgqqtx.html