uni-app 服務(wù)端請求封裝

自己封裝的uni-app服務(wù)端請求,包括 異常捕獲、loading開啟關(guān)閉、特殊請求基礎(chǔ)地址、header的token配置、請求編碼為application/json或application/x-www-form-urlencoded

http.js

// created by wangyong for uni-app request 2019.11.22
const baseURL = 'http://localhost:8888/vec';
const http = (options) => {
    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: '加載中...',
            mask: options.load || false // 默認(rèn)遮罩出現(xiàn)可以繼續(xù)操作
        });
        try{
            uni.request({
                url: (options.baseURL || baseURL) + options.url,
                method: options.method || 'POST', // 默認(rèn)為POST請求
                data: options.data, //請求超時(shí)在manifest.json配置
                header: {
                    'v-token': '333333',
                    'Content-Type': options.header == 'form' ? 'application/x-www-form-urlencoded' : 'application/json'
                },
                success: res => {
                    resolve(res.data)
                },
                fail: (err) => {
                    reject(err.data);
                    console.log(err);
                    uni.showToast({
                        title: '請檢查網(wǎng)絡(luò)連接',
                        icon: 'none'
                    })
                    /*錯(cuò)誤碼處理
                    let code = err.data.code; 
                    switch (code) {
                        case 1000:
                            break;
                        default:
                            break;
                    } */
                },
                complete: () => {
                    uni.hideLoading();
                }
            });
        }catch(e){
            uni.hideLoading();
            uni.showToast({
                title: '服務(wù)端異常',
                icon: 'none'
            })
        }
        
    })
}

export default http

main.js 添加

import http from './common/http.js'

Vue.prototype.$HTTP = http

調(diào)用實(shí)例:

this.$HTTP({
  method: 'POST',
  url: '/api/news',
  data: {},
 // baseURL:'http://www.buwang.com'
 // header:'form' 
}).then((res) =>{
  console.log(res)
}
// (err)=>{ console.log(err) }
)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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