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

 

分类:

技术点:

相关文章:

  • 2021-09-21
  • 2022-01-12
  • 2021-05-02
  • 2021-03-31
  • 2021-07-06
  • 2021-05-24
  • 2021-12-16
  • 2021-11-20
猜你喜欢
  • 2021-07-06
  • 2021-05-08
  • 2021-11-20
  • 2021-12-05
  • 2021-12-25
  • 2021-05-25
  • 2021-07-01
相关资源
相似解决方案