微信小程序:wx.request請求封裝工具類

修改過的封裝請求:

header: {'Content-Type': 'application/json'},  防止參數中敏感字符丟失的問題

header: {'Content-Type': 'application/x-www-form-urlencoded'},  

function Requests(url, data) {
  return new Promise((resolv, reject) => {
    wx.request({
      url: url,
      data: data,
      method: "get",
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data == "服務器異常") {
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: '網絡錯誤或服務器繁忙!',
          })
        } else {
          resolv(res.data)
        }
      },
      fail: function(err) {
        console.log(err)
        reject(err)
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '網絡錯誤或服務器繁忙!',
        })
      }
    })
  })
}

function Requests_json(url, data) {
  return new Promise((resolv, reject) => {
    wx.request({
      url: url,
      data: data,
      method: "POST",
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        if (res.data == "服務器異常") {
          wx.hideLoading()
          wx.showModal({
            title: '提示',
            content: '網絡錯誤或服務器繁忙!',
          })
        } else {
          resolv(res.data)
        }
      },
      fail: function(err) {
        wx.hideLoading()
        console.log(err)
        reject(err)
        wx.showModal({
          title: '提示',
          content: '網絡錯誤或服務器繁忙!',
        })
      }
    })
  })
}

把封裝請求函數暴露出去:

module.exports = {
  Requests,
  Requests_json
}

使用:

var config = require('../../../config.js')
var util = require('../../../utils/util.js')


util.Requests_json(請求接口路徑, 需要攜帶的參數).then((res) => {
     console.log(res)
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章