微信小程序HTTPS接口請求封裝


微信小程序開發過程中,經常會用到 wx:request 方法發起HTTPS網絡請求來調用后台的接口方法,過多的調用會產生代碼冗余,本篇博客介紹如何在微信小程序中封裝HTTPS接口請求

wx:request官方文檔:https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html

1、封裝方法

在 utils 文件夾下添加 request.js 文件,添加如下代碼

var app = getApp(); //獲取小程序全局唯一app實例
var host = '******************'; //接口地址

//url:接口
//postData:參數
//doSuccess:成功的回調函數
//doFail:失敗的回調函數

//POST請求
function post(url, postData, doSuccess, doFail) {
  request(url, postData, "POST", doSuccess, doFail);
}

//GET請求
function get(url, postData, doSuccess, doFail) {
  request(url, postData, "GET", doSuccess, doFail);
}

function request(url, postData, method, doSuccess, doFail) {
  wx.showLoading({
    title: "正在加載中...",
  })
  wx.request({
    url: host + url, //請求地址
    method: method, //請求方法
    header: { //請求頭
      "Content-Type": "application/json;charset=UTF-8"
    },
    data: postData, //請求參數    
    dataType: 'json', //返回數據格式
    responseType: 'text', //響應的數據類型
    success: function(res) {
      wx.hideLoading();
      //成功執行方法,參數值為res.data,直接將返回的數據傳入
      doSuccess(res.data);
    },
    fail: function() {
      //失敗執行方法
      doFail();
    },
  })
}
//module.exports用來導出代碼
//js文件中通過var http = require("../../util/request.js")加載
module.exports = {
  postRequest: post,
  getRequest: get,
}

tips:請求頭 header 默認為 application/json ,如果設置不校驗合法域名、web-view(業務域名)、TLS版本以及HTTPS證書,需修改請求頭 header為HTTP請求頭: application/x-www-form-urlencoded,否則post請求時將會報錯,正式開發環境中可忽略,直接使用默認請求頭 application/json

2、調用方法

2.1 .js文件中引入request.js文件

var http = require('../../utils/request.js'); //相對路徑

tips:注意路徑正確與否,若請求報錯可考慮是路徑問題

2.2 調用請求方法(post請求為例)

var params = {//請求參數
  aid: this.optionaid, //id
  aname: this.data.receiving, //收貨人
  atell: this.data.tell, //聯系方式
  adetailed: this.data.detailed, //詳細地址
}
http.postRequest("EditAddress/EditAddressInfo", params, function(res) {
  console.log("修改成功!");
  wx.navigateTo({
    url: '/pages/address/address',
  })
}, function(res) {
  console.log("修改失敗!!!")
})

End!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM