微信小程序request封裝,小程序封裝接口請(qǐng)求

request封裝可以方便我們統(tǒng)一管理請(qǐng)求函數(shù),減少冗余代碼。

const baseUrl = "xxx"; //請(qǐng)求根

const http = ({
    url = "",
    param = {},
    type = 'from',
    ...other
} = {}) => {
    wx.showLoading({ //可以不加
        title: '請(qǐng)求中...'
    })
    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(`耗時(shí)${Date.now() - timeStart}`);
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data);
                    ... //此處根據(jù)自己的業(yè)務(wù)需求自行定義
                } else {
                    reject(res)
                }
            }
        })
    })
}

使用實(shí)例

// 1.無需傳參數(shù)請(qǐng)求(默認(rèn)get請(qǐng)求,header為from)
const a = () => {
    return http({
        url: 'xxx',
    })
}

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

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

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

頁(yè)面中使用

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=>{}) 
}

//如果頁(yè)面有多個(gè)請(qǐng)求同時(shí)進(jìn)行,可以這樣寫
Promise.all([
  api.a,
  api.b,
]).then(res =>{}).catch(err=>{})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容