caicaiz

封装uni.request()接口的 util/api.js文件:

// 二次封装请求接口
const BASE_URL = \'http://localhost:8082\'
 
export const myRequest = (options) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: BASE_URL + options.url,
            method: options.method || \'GET\',
            data: options.data || {},
            success: (res) => {
                if(res.data.status !== 0){
                    return uni.showToast()({
                        title: \'获取数据失败\'
                    })
                }
                resolve(res)
            },
            fail: (err) => {
                uni.showToast()({
                    title: \'请求接口失败\'
                })
                reject(err)
            }
        })
    })
}

然后在main.js文件内进行导入和全局挂载

import { myRequest } from \'./util/api.js\'
 
Vue.prototype.$myRequest = myRequest

页面使用 (通过这个$myRequest进行访问接口,并获取数据)

async getData(){
    const res = await this.$myRequest({
        url: \'/api/test\'
    })
    conso le.log(res.data)
}

 

分类:

技术点:

相关文章: