微信小程序获取接口的封装

接口封装微信小程序

1:第一步在pages同层级创建一个config文件然后里面创建一个config.js文件 里面写入:

const config = {
  url : "http://jd.itying.com/api"      //你要请求数据的公共接口
};

export {config}   导出

2:第二步在utils文件里创建一个request.js文件然后:

//引入config文件 --- 项目的公共接口
import {config} from "../config/config"

//接口的错误提示码       一般根据给的文档放入报错的状态码
const tips = {     
  1: '抱歉,出现了一个错误',
  1005:'appkey无效,请前往www.7yue.pro申请',
  3000:'期刊不存在'
}

class HTTP {

  request({url,data={},method = "GET"}){
    return new Promise((resolve,reject)=>{
      this._request(url,resolve,reject,data,method)
    })
  };

  _request(url,resolve,reject,data={},method="GET"){
    wx.request({
      url: config.url + url,
      method : "GET",
      data : data,
      header : {},
      success : (response)=>{
    
    const code = response.statusCode.toString();
    if(code.startsWith("2")){
      resolve(response);
    }else{
      reject();
      const error_code = response.data.error_code //1005
      this._show_error(error_code)
    }

  },
  fail : function(error){
    reject(error)
    this._show_error(1);
  }
})
  }

  _show_error(error_code){
  // 1005
    if(!error_code){
      error_code = 1
    }                   // 1005
    const tip = tips[error_code]
    wx.showToast({
        title: tip?tip:tips[1], 
        icon:'none',
        duration:2000
    }) 
  }
}
export {HTTP}    //最后导出HTTP

3:一般我是再创建一个model文件然后里面(比如要获取首页的数据)就创建一个index.js文件。如果页面数据多的话,可以每个页面都创建一个对应的js文件。里面写入:

import {HTTP} from "../utils/request"    //引入封装好的HTTP

class IndexModel extends HTTP {
  //比如这是获取轮播图的数据
  getBanner(){
    return this.request({url : "/focus"});   //公共接口已经封装过了,这里只写后面的接口
  };
}

export {IndexModel}    //最后导出

4:最后一步在需要获取数据的页面中写入:

//1:首先在最上面引入
import {IndexModel} from "../../model/indexModel"
const indexModel = new IndexModel();

//2:然后我一般在这个生命周期中:
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //请求到了轮播图的数据
    indexModel.getBanner().then(response=>{
      console.log(response)
    });
  }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默默无闻的FYH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值