微信小程序提供了網絡請求的API,我們之所以還要封裝是因爲如果開發的項目比較大,網絡請求的地方很多,直接使用小程序自己提供的API 會非常麻煩,每次都要寫很多重複性代碼,所以對網絡請求封裝非常必要。
首先新建一個service文件
service 文件夾 ->network.js
import { baseURL, timeout } from './config.js'
function request(options) {
wx.showLoading({
title: '數據加載中ing',
})
return new Promise((resolve, reject) => {
wx.request({
url: baseURL + options.url,
timeout: timeout,
data: options.data,
success: function(res) {
resolve(res.data)
},
fail: reject,
complete: res => {
wx.hideLoading()
}
})
})
}
export default request;
然後在需要網絡請求的js文件導入,導入的方式是
import request from '/service/network.js'
導入之後使用封裝的request發送的網絡請求
request({
url:‘xxxxxxxx’,
method:'POST',
}).then(res=>{
console.log(res)
}).catch( err=>{
console.log(err)
})
//promise 最大的好處是避免出現回調地獄。
service->config.js
export const baseURL = 'http://123.207.32.32:8000'
export const timeout = 5000