微信小程序request請求封裝

在項目中獲取後臺數據時,會應用到 wx.request({}) 發起https網絡請求。

項目中需求:如果是 POST請求 接口, 進行 MD5加密。 根據實際需求即可。

寫的不好,歡迎大神們指點。謝謝!

API

wx.request網絡請求API

參考文章

完整request請求

爲了方便查看, 這裏分開寫。需要使用者,可以直接按順序copy即可。

MD5.JS

微信小程序使用md5加密參考:

//獲取應用實例
const app = getApp()
import md5 from 'md5.js';
var TOKEN_KEY = 'Authorized-Token'



var url ='https://域名';
var rootDocment = url+'/api/';
var header = {
  'Accept': 'application/json',
  'content-type': 'application/json',
}

GET請求

// toast作用: 請求接口時, 顯示loadding

function getReq(url, cb, toast = true) {
    var token = wx.getStorageSync(TOKEN_KEY) || ''
    if (token) {
        header[TOKEN_KEY] = token;
    }
    if (toast) {
        wx.showLoading({
            title: '加載中',
        })
    }

    // console.log("token==" + token),
    wx.request({
        url: rootDocment + url,
        method: 'get',
        header: header,
        success: function (res) {
            if (toast) {  
                wx.hideLoading();
            }
            return  response_chuli(res, cb);
        },
        fail: function () {
            if (toast) {  
                wx.hideLoading();
            }
            wx.showModal({
                title: '網絡錯誤',
                content: '網絡出錯,請刷新重試',
                showCancel: false
            })
            return typeof cb == "function" && cb(false)
        }
    })
}

POST請求

// toast作用: 請求接口時, 顯示loadding, 默認"顯示"
function postReq(url, data, cb, toast = true) {
    var token = wx.getStorageSync(TOKEN_KEY) || ''
    if (token) {
        header[TOKEN_KEY] = token;
    }
    if (toast){
        wx.showLoading({
            title: '加載中',
        })
    }
    
    //以下是 md5加密相關
    var appkey ='Abcdefghigk2019';  //測試
    var newObj = objKeySort(data);  //數據排序
    //console.log(newObj);
    let connects = '';
    for(let item in newObj){
        connects += newObj[item];
    }
    // 拼接格式登錄: 15899999999123456Abcdefghigk2019  進行加密
    connects += appkey;

    //console.log(connects);
    data.sign = md5(connects);

    //console.log("header=="+token),
    //console.log(header),
    
    //指定某個接口使用表單提交
    if(url=='user/test'){
        header['Accept'] = '*/*';
        header['content-type'] = 'application/x-www-form-urlencoded';
    }

    wx.request({
        url: rootDocment + url,
        header: header,
        data: data,
        method: 'post',
        success: function (res) {
            if (toast) {  
                wx.hideLoading();
            }
            return   response_handle(res, cb);
        },
        fail: function () {
            if (toast) {
                wx.hideLoading();
            }
            wx.showModal({
                title: '網絡錯誤',
                content: '網絡出錯,請刷新重試',
                showCancel: false
            })
            return typeof cb == "function" && cb(false)
        }
    })

}

返回數據處理

//返回處理
function response_handle(res, cb) {
    if (401 === parseInt(res.status) || 401 === parseInt(res.data.code)) {
        //清除緩存
        wx.setStorageSync(TOKEN_KEY, '');
        wx.setStorageSync('userinfo', '');

        wx.navigateTo({
            url: '/pages/wxlogin/wxlogin?from=index' 
        })
        return ;

    } else if (200 === parseInt(res.data.code)){
        var t = res.header[TOKEN_KEY] || "";
        t && wx.setStorageSync(TOKEN_KEY, t);
    } 
    return typeof cb == "function" && cb(res.data)
}

JSON數據排序方法

//json數據排序
function objKeySort(obj,typesort = 'sort') {//排序的函數
    if(typesort == 'sort') {
        var newkey = Object.keys(obj).sort(); //升序
    }else {
        var newkey = Object.keys(obj).sort().reverse(); //降序
    }
    //先用Object內置類的keys方法獲取要排序對象的屬性名,再利用Array原型上的sort方法對獲取的屬性名進行排序,newkey是一個數組
    var newObj = {};//創建一個新的對象,用於存放排好序的鍵值對
    for (var i = 0; i < newkey.length; i++) {//遍歷newkey數組
        newObj[newkey[i]] = obj[newkey[i]];//向新創建的對象中按照排好的順序依次增加鍵值對
    }
    return newObj;//返回排好序的新對象
}

導出模塊

module.exports = {
    getReq: getReq,
    postReq: postReq,
    header: header,
    rootDocment: rootDocment,
    url: url,
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章