uni-app请求接口封装

uniapp使用类封装接口

大致分为三步

1 封装请求
2 定义接口
3 页面调用

1 在项目根目录下新建utils文件夹,该文件夹存放公共方法,新建http.js,内容入下
官方变量区分

// 区分环境 ,HbuilderX编辑运行时dev开发环境,发行后自动时生成环境
let baseUrl = ''
if (process.env.NODE_ENV === 'development') {
  console.log('开发环境')
  baseUrl = 'https://cnodejs.org/api/v1/';
} else {
  console.log('生产环境')
  baseUrl = 'https://cnodejs.org/api/v1/';
}
class Model {
  //定义接口
  api(opts = {}) {
    //监听网络链接
    uni.onNetworkStatusChange((res) => {
      if (!res.isConnected) {
        uni.showToast({
          title: '网络连接不可用!',
          icon: 'none'
        });
      }
      return false
    });
    //定义参数对象
    if (!opts.method) opts.method = 'get'
    if (opts.domain) baseUrl = opts.domain
    // token
    let token = ''
    // 鉴权
    let authorize = ''
    if (uni.getStorageSync('token')) token = uni.getStorageSync('token')
    if (uni.getStorageSync('Authorization')) authorize = uni.getStorageSync('Authorization')
    // 前端自定义token失效
    // if (token == '' || token == undefined || token == null) {
    //   uni.showToast({
    //     title: '账号已过期,请重新登录',
    //     icon: 'none',
    //     complete: function() {
    //       uni.reLaunch({
    //         url: '/pages/login/index'
    //       });
    //     }
    //   });
    // }
    let header = {
      Authorization: authorize,
      'Content-Type': 'application/json; charset=UTF-8'
    }
    // 删除鉴权
    if (opts.noAuth) {
      delete header.Authorization
    }
    return new Promise((resolve, reject) => {
      uni.request({
        url: baseUrl + opts.url,
        data: opts.data,
        method: opts.method,
        header: header,
        success: res => {
          if (res.statusCode === 200) {
            if (res.data) {
              resolve(res.data);
              // token过期
            } else if (res.data.returnCode === '401') {
              uni.showModal({
                title: '提示',
                content: '登录过期,请重新登录',
                success: function(res) {
                  if (res.confirm) {
                    uni.redirectTo({
                      url: '/pages/login/index'
                    });
                    uni.clearStorageSync();
                  } else if (res.cancel) {
                    uni.switchTab({
                      url: '/pages/work/index'
                    });
                  }
                }
              });
              resolve(res.data);
            } else {
              uni.showToast({
                title: res.data.returnMessage,
                icon: 'none',
                duration: 1500
              });
              reject(res.data);
            }
          }
        },
        fail: () => {
          console.log('请求失败,请稍候重试');
          uni.hideLoading();
          uni.showToast({
            title: 'net error!',
            icon: 'none',
            duration: 1500
          });
        }
      });
    })
  }

  get(options = {}) {
    options.method = 'GET'
    return this.api(options)
  }
  post(options = {}) {
    options.method = 'POST'
    return this.api(options)
  }
  put(options = {}) {
    options.method = 'PUT'
    return this.api(options)
  }
  delete(options = {}) {
    options.method = 'DELETE'
    return this.api(options)
  }
}

export default Model

2 根目录新建model文件夹,用来存放接口,新建接口文件,我这边测试用cnode社区接口

// 导入类
import Model from '@/utils/http.js'
// const baseUrl = 'https://cnodejs.org/api/v2'
//继承类的方法
class Cnode extends Model {
  constructor(baseUrl) {
    super(baseUrl)
    this.baseUrl = baseUrl
  }
  //获取文章数据 //定义接口名
 // get
  getTopics(options) {
    console.log(options);
    options.url = `topics?page=${options.data.page}`
    // 做本地自定义联合调试用
    // options.domain = `http:172.168.0.0.1:8080/`
    return this.get(options)
  }

 // post
  postxxx (options) {
    options.url = '/api/xxx'
    return this.post(options)
  }
}
const cnodeModel = new Cnode()
export default cnodeModel

3 页面调用

<script>
import cnodeModel from '@/model/cnode.js';
console.log(cnodeModel);
export default {
  data() {
    return {
      params: {
        page: 1
      }
    };
  },
  onLoad() {},
  onShow() {
    this.getTopics();
  },
  methods: {
    getTopics() {
      let opts = {
        data: { page: 1 }
      };
      cnodeModel.getTopics(opts).then(res => {
        console.log(res);
      });
    }
  }
};
</script>

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值