小程序封裝request請求


為了減少代碼量 以及方便后期的維護 ,把小程序中的request請求封裝起來是很有用的

建一個和page同級的文件夾http

1.建立一個nev.js 文件 封裝各個環境下的公共接口

  module.exports={
    //開發環境
    dev:{
      baseUrl:'http://127.0.0.1:8080'
    },
    //生產環境
    prod:{
      baseUrl:'https://api.it120.cc'
    },
    //測試環境
    test:{
      baseUrl:'https://api.1909A.com'
    }
  }

2.建立一個reque.js 文件 封裝request核心ajax請求

  const { baseUrl } = require('./env.js').prod
  //封裝ajax
  const vipUrl='專屬域名'
  module.exports={
    request:function(url,method="GET",data={},isSubDomain=true) {
      let fullUrl = `${baseUrl}/${isSubDomain ? vipUrl:''}/${url}`;
        //數據請求成功前的loading加載
       wx.showLoading({
         title: '玩命加載中',
       })
        //promise封裝request
       return new Promise((resolve,reject)=>{
           wx.request({
             url: fullUrl,
             method,
             data,
             header:{
               'Content-type':'application/x-www-form-urlencoded'
             },
             success(res){
              // console.log('res::',res)
                 //數據請求成功判斷
               if (res.statusCode===200 && res.data.code===0) {
                  resolve(res.data.data)
                  wx.hideLoading()
               }else {
                 wx.showToast({
                   title: '接口有問題,請檢查',
                 })
                 reject('接口有問題,請檢查')
               }
             },
             fail(error) {
               wx.showToast({
                 title: '數據接口有問題',
               })
               reject('數據接口有問題')
             }
           })
       })
    }
  }

3.建立api.js 封裝各個接口

  const { request }=require('./request.js');

  //項目中用到的各種業務接口的封裝

  module.exports={

    //商品分類接口
    goodsCate:()=> {

      return request('shop/goods/category/all','GET','',true)

    },
    //banner圖接口
    getBanner:()=>{},
    //商品詳情接口
    getDetail:(id)=>{

      return request('shop/goods/detail','GET',{id:id},true)
    },
    //其他接口....

  }

4.找一個一個需要接口的頁面 在他對應的js 頁面引入

  //通過結構賦值的方式~
  const { goodsCate, getDetail}=require('../..//http/api.js')
  Page({
        data:{
              desc:[]
        },
       onShow(e) {
          var that = this;
           goodsCate().then(res=>{
                 console.log('index.js中接收:',res)
             })
                //   let id=e.detail
            getDetail(395742).then(res=>{
                 console.log('商品詳情:',res.content)
                 this.setData({
                      desc: res.content
                 })
              WxParse.wxParse('article', 'html', that.data.desc, that, 5);
          })
    })
小程序封裝request請求和vue封裝axios請求的思想其實是一樣的 主要都是通過promise來實現的,網絡請求是項目中必不可少的,其封裝的思想一定要知道的!
每天一個小知識點,一點一點的成長,加油!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM