微信小程序request封裝,小程序封裝接口請求

request封裝可以方便我們統一管理請求函數,減少冗余代碼。

const baseUrl = "xxx"; //請求根

const http = ({
    url = "",
    param = {},
    type = 'from',
    ...other
} = {}) => {
    wx.showLoading({ //可以不加
        title: '請求中...'
    })
    let timeStart = Date.now();
    return new Promise((resolve, reject) => {
        wx.request({
            url: baseUrl + url,
            data: param,
            header: { //兩種  ,一種json 一種 from
                'content-type': type == 'from' ? 'application/x-www-form-urlencoded' : 'application/json'
            },
            ...other,
            complete: res => {
                wx.hideLoading(); //同上 ,可以不加
                console.log(`耗時${Date.now() - timeStart}`);
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data);
                    ... //此處根據自己的業務需求自行定義
                } else {
                    reject(res)
                }
            }
        })
    })
}

使用實例

// 1.無需傳參數請求(默認get請求,header為from)
const a = () => {
    return http({
        url: 'xxx',
    })
}

// 2.帶參數請求并且為post
const b = param => {
    return http({
        url: 'xxx',
        method: 'post'
    })
}

// 3.帶參數請求post,header為json
const c = param => {
    return http({
        url: 'xxx',
        type: 'json',
        method: 'post'
    })
}

module.exports = {
    a,
    b,
    c,
}

頁面中使用

const api = require(xxxx); //找到我們封裝的api

requestA() {
        api.a().then(res=> {
            console.log(res);
        }) .catch(err =>{
            console.log(err);
        }) 
},
requestB() {
    let data = {}
    api.b(data).then(res => {}).catch(err=>{}) 
}

//如果頁面有多個請求同時進行,可以這樣寫
Promise.all([
  api.a,
  api.b,
]).then(res =>{}).catch(err=>{})
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。