1. 程式人生 > >微信小程式:request請求封裝工具類

微信小程式: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)
})