天天看點

微信小程式請求封裝

小程式官方有自己網絡請求的api,但這種寫法不好去維護,耦合度太高,也容易出現回調地獄。

wx.request({
	  url: 'test.php', //僅為示例,并非真實的接口位址
	  data: {
	    x: '',
	    y: ''
	  },
	  header: {
	    'content-type': 'application/json' // 預設值
	  },
	  success (res) {
	    console.log(res.data)
	  }
	})
           

封裝:

  1. 建立一個api檔案,裡面建立一個configUrl.js和request.js兩個js檔案。
  2. configUrl.js裡是用來放我們請求的域名的
  1. request.js是用來封裝請求的檔案。這裡我們使用es6的promise進行封裝。首先引入configUrl ,然後在官方api基礎上進行封裝:
import configUrl from './configUrl.js'
	export default function request(options){
		retun new Promise((reslove,reject)=>{
			wx.request({
			  url: configUrl+options.url,
			  method: options.method||'get',
			  data: options.data||{},
			  header: {
			    'content-type': 'application/json',
			    'Authorization': 'Bearer ' + wx.getStorageSync('token')
			  },
			  success (res) {
			    reslove(res)
			  },
			  fail(err){
			 	reject(err)
			  }
			})
		})
	}
           
  1. 在頁面調用封裝的請求
import request from '/api/request.js'
	request({
		url:'/article-list',
		method:'get',
		data:{type:'social'}
	}).then(res=>{
	
	}).catch(err=>{
	
	})