uniapp 請(qǐng)求封裝

1、utils文件夾下新建request.js

// 此vm參數(shù)為頁面的實(shí)例,可以通過它引用vuex中的變量
import {baseUrl} from './baseUrl.js'
module.exports = (vm) => {
    // 初始化請(qǐng)求配置
    uni.$u.http.setConfig((config) => {
        /* config 為默認(rèn)全局配置*/
        config.baseURL = baseUrl; /* 根域名 */
        //config.baseURL = 'http://124.128.14.146:38004/fmis-api/'; /* 根域名 */
        return config
    })
    
    // 請(qǐng)求攔截
    uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做異步操作
            uni.showLoading({
                title:'請(qǐng)求中'
            })
            let mpopenId = uni.getStorageSync('mpopenId')
        // 初始化請(qǐng)求攔截器時(shí),會(huì)執(zhí)行此方法,此時(shí)data為undefined,賦予默認(rèn){}
        config.data = config.data || {}
        // 根據(jù)custom參數(shù)中配置的是否需要token,添加對(duì)應(yīng)的請(qǐng)求頭
        if(config?.custom?.auth) {
            // 可以在此通過vm引用vuex中的變量,具體值在vm.$store.state中
            config.header.token = vm.$store.state.userInfo.token
        }
        if(mpopenId){
            config.header.openId = mpopenId
        }
        return config 
    }, config => { // 可使用async await 做異步操作
        return Promise.reject(config)
    })
    
    // 響應(yīng)攔截
    uni.$u.http.interceptors.response.use((response) => { /* 對(duì)響應(yīng)成功做點(diǎn)什么 可使用async await 做異步操作*/
        uni.hideLoading()
        const data = response.data
        //console.log(data,data.code,'request')
        // 自定義參數(shù)
         // const custom = response.config?.custom
        if (data.code == 0) {
            //console.log(data,'00')
            // return uni.showToast({
            //  title:data.message,
            //  icon:'none'
            // })
            return data 
        }else{
            return data.data  ? data.data : data
        }
        
    }, (response) => { 
        uni.hideLoading()
        // console.log(response,'報(bào)錯(cuò)')
         uni.$u.toast("請(qǐng)求失敗")
        // 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么 (statusCode !== 200)
        return Promise.reject(response)
    })
}

2、在main.js文件引用

const app = new Vue({
  ...App
})
require("./utils/request.js")(app)
app.$mount()

3、定義使用

export const getData= (params, config = {}) => uni.$u.http.post('/a/getData', params, config)

在頁面使用時(shí)

import { getData } from '@/api/index.js'
async loadDays() {
  let res = await getData ({})
  console.log(res, 'res')
},
?著作權(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ù)。

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

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