微信接口請求帶token封裝


var apiHost = "地址";
var tokenKey = "token";
// 登錄地址, 根據這個地址來設置token
var logInUrl = "/Account/LogInForMiniProgram";
// 例外不用token的地址
var exceptionAddrArr = [
  'http://localhost:8080',
];
 
/** 
 * @param url:String  require(必需) 請求地址相對路徑
 * @param data:Object   可選  請求數據
 * @param success:Function  可選   成功回調函數
 * @param fail:Function     可選    失敗回調函數
 */
function getRequest(url, data, success, fail) {
  CreateHeader(url, function (header) {
    wx.request({
      url: apiHost + url,
      method: 'GET',
      data: data,
      header: header,
      success: function (res) {
        if (success && typeof success === "function") {
          success(res);
        }
      },
      fail: function (error) {
        if (fail && typeof fail === "function") {
          fail(error);
        } else {
          console.log(error);
        }
      }
    })
  });
}
/** 
 * @param url:String  require(必需) 請求地址相對路徑
 * @param data:Object   可選  請求數據
 * @param success:Function  可選   成功回調函數
 * @param fail:Function     可選    失敗回調函數
 */
function postRequest(url, data, success, fail) {
  CreateHeader(url, function (header) {
    wx.request({
      url: apiHost + url,
      method: 'POST',
      data: data,
      header: header,
      success: function (res) {
        if (url === logInUrl) {
          wx.setStorage({
            key: tokenKey,
            data: res.data.result
          })
        }
        if (success && typeof success === "function") {
          success(res);
        }
      },
      fail: function (error) {
        if (fail && typeof fail === "function") {
          fail(error);
        } else {
          console.log(error);
        }
      }
    })
  });
}
 
/** 
 * @param url:String    請求地址(根據請求地址判斷是否添加token)
 * @param complete:Function 回調函數
 */
function CreateHeader(url, complete) {
  var header = {
    'content-type': 'application/json'
  }
  if (exceptionAddrArr.indexOf(url) == -1) {  //排除請求的地址不需要token的地址
    wx.getStorage({
      key: tokenKey,
      success: function (res) {
        header.Authorization = 'Bearer ' + res.data;
      },
      fail: function (error) {
        console.log(error);
      },
      complete: function () {
        complete && typeof complete === 'Function' ? complete(header) : null;
      }
    });
  } else {
    complete && typeof complete === 'Function' ? complete(header) : null;
  }
}
 
module.exports.getRequest = getRequest;
module.exports.postRequest = postRequest;


免責聲明!

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



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