小程序封裝request請求


小程序開發請求提供了api,wx.request(),方便管理,可以對請求進行封裝。

 

實現:創建一個api文件夾

1.創建urls.js文件,用於url管理

 

2.創建request.js,用於實現對wx.request()的封裝

import urls from './urls'

const service = {
  get (url,data) {
    return new Promise((resolve,reject) => {
      wx.request({
        method: 'get',
        url: url,
        data: data,
        header: {"content-type": "application/json"},
        success: (res) =>{
          // 調用接口成功
          resolve(res)
        },
        fail: (err) => {
          // 調用接口失敗
          reject(err)
        }
      })
    })
  },
  post (url,data) {
    return new Promise((resolve,reject) => {
      wx.request({
        method: 'post',
        url: url,
        data: data,
        header: {"content-type": "application/x-www-form-urlencoded"},
        success: (res) =>{
          // 調用接口成功
          resolve(res)
        },
        fail: (err) => {
          // 調用接口失敗
          reject(err)
        }
      })
    })
  }
}

module.exports = {
  // 獲取4個功能展示位
  getSales: (data) => {
    return new Promise((resolve,reject)=> {
      resolve(service.get(urls.sales,data))
    })
  },
  // 獲取所有分類列表
  getCateList: (data) => {
    return new Promise((resolve,reject)=> {
      resolve(service.get(urls.cateList,data))
    })
  }
}

  

3.具體在需要的頁面中調用

 

onLoad: function() {
    var that = this;
    that._getBanner()
    that._getSales()
}

 

 

 

  

 


免責聲明!

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



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