微信小程序已經(jīng)成為了人們?nèi)粘I钪斜夭豢缮俚囊徊糠?。隨著微信小程序平臺(tái)的發(fā)展,開發(fā)者們也有了更多的可操作性。在這里,我們將探討微信小程序網(wǎng)絡(luò)請(qǐng)求的相關(guān)問題,為您提供一系列解決方案,幫助您提高代碼復(fù)用。
一、問題
微信小程序網(wǎng)絡(luò)請(qǐng)求常常遇到的問題之一就是請(qǐng)求方法的重復(fù)使用。當(dāng)您有多個(gè)頁面需要調(diào)用同一個(gè)接口時(shí),如果每個(gè)頁面都去寫一次請(qǐng)求代碼的話,豈不是太過于冗余了嗎?這樣一來,不僅增加了代碼的復(fù)雜度,還浪費(fèi)了代碼書寫的時(shí)間成本。因此,通用請(qǐng)求方法的封裝是必不可少的。
二、解決方案
1.統(tǒng)一請(qǐng)求方法封裝
在微信小程序中,網(wǎng)絡(luò)請(qǐng)求可以通過 wx.request() 方法進(jìn)行調(diào)用。為了提高代碼復(fù)用性,我們可以使用封裝通用請(qǐng)求方法的方式,將請(qǐng)求代碼統(tǒng)一管理起來。例如:
```
//app.js中定義請(qǐng)求方法
App({
globalData: {},
apiUrl: 'https://www.example.com',
request(url, data = {}, method = 'GET') {
const token = wx.getStorageSync('token');
return new Promise((resolve, reject) => {
wx.request({
url: `${this.apiUrl}${url}`,
method,
data,
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${token}`
},
success: (res) => {
resolve(res.data);
},
fail: (err) => {
reject(err);
}
})
})
}
})
```
這里我們將請(qǐng)求方法封裝在了 app.js 中,并設(shè)置了全局的 apiUrl 和 header 參數(shù),讓所有的請(qǐng)求方法都可以使用。
2.調(diào)用請(qǐng)求方法
當(dāng)我們需要在單個(gè)頁面中調(diào)用請(qǐng)求方法時(shí),只需引用 app.js 文件中定義的全局函數(shù),而不用在每個(gè)頁面中分別書寫請(qǐng)求代碼。例如:
```
//index.js中調(diào)用請(qǐng)求方法
const app = getApp();
Page({
data: {
list: []
},
onLoad() {
this.getList();
},
getList() {
app.request('/list').then(res => {
this.setData({
list: res,
})
})
}
})
```
這里我們?cè)?index.js 中直接使用 app.js 文件中定義的請(qǐng)求方法,同時(shí)也得到了 app.js 中設(shè)置的全局 apiUrl 和 header 參數(shù)。
3.傳遞參數(shù)
在封裝通用請(qǐng)求方法時(shí),我們也需要考慮到一些特殊情況,例如有多個(gè)參數(shù)需要傳遞時(shí)。在這種情況下,可以使用 ES6 的解構(gòu)賦值來傳遞參數(shù),例如:
```
//app.js中定義請(qǐng)求方法
request(url, { data, method = 'GET', header } = {}) {}
//index.js中調(diào)用請(qǐng)求方法
app.request('/list', {
data: {
page: 1,
limit: 10
},
header: {
'Content-Type': 'application/json',
}
})
```
在這里,我們對(duì) data、method 和 header 這三個(gè)參數(shù)使用了解構(gòu)賦值,并給了默認(rèn)值。在調(diào)用請(qǐng)求方法時(shí),我們可以根據(jù)參數(shù)需要直接傳遞 {}
4.錯(cuò)誤處理
在實(shí)際開發(fā)中,網(wǎng)絡(luò)請(qǐng)求不可避免會(huì)出現(xiàn)錯(cuò)誤,例如網(wǎng)絡(luò)故障等等。因此,在請(qǐng)求方法中,我們需要加入錯(cuò)誤處理的邏輯,例如:
```
//app.js中定義請(qǐng)求方法
request(url, { data, method = 'GET', header } = {}) {
const token = wx.getStorageSync('token');
return new Promise((resolve, reject) => {
wx.request({
url: `${this.apiUrl}${url}`,
method,
data,
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${token}`,
...header,
},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data);
} else {
reject(res);
}
},
fail: (err) => {
reject(err);
}
})
})
}
//index.js中調(diào)用請(qǐng)求方法
app.request('/list').then(res => {
this.setData({
list: res,
})
}).catch(err => {
console.error(err);
})
```
在這里,我們加入了錯(cuò)誤處理邏輯,如果請(qǐng)求成功,則返回請(qǐng)求結(jié)果。而如果請(qǐng)求失敗,則會(huì)進(jìn)入 catch 塊中處理錯(cuò)誤邏輯。
5.優(yōu)化請(qǐng)求方法
在某些場(chǎng)景下,我們需要進(jìn)行數(shù)據(jù)緩存。例如我們需要展示的列表數(shù)據(jù),并不是實(shí)時(shí)獲取的。此時(shí),我們可以進(jìn)行數(shù)據(jù)緩存優(yōu)化,例如:
```
//app.js中定義請(qǐng)求方法
request(url, { data, method = 'GET', header } = {}, cache = false) {
const token = wx.getStorageSync('token');
const cacheKey = `${url}-${JSON.stringify(data)}`;
if (cache && wx.getStorageSync(cacheKey)) {
return Promise.resolve(wx.getStorageSync(cacheKey));
}
return new Promise((resolve, reject) => {
wx.request({
url: `${this.apiUrl}${url}`,
method,
data,
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${token}`,
...header,
},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data);
} else {
reject(res);
}
},
fail: (err) => {
reject(err);
}
})
}).then(res => {
wx.setStorageSync(cacheKey, res);
return res;
})
}
//index.js中調(diào)用請(qǐng)求方法
app.request('/list', {}, true);
```
在這里,我們添加了 cache 參數(shù)控制是否開啟緩存,并使用 wx.setStorageSync() 和 wx.getStorageSync() 實(shí)現(xiàn)數(shù)據(jù)緩存。當(dāng)然,這種方式需要考慮到cache超時(shí)時(shí)間的問題。
三、總結(jié)
通過以上的解決方案,我們可以將通用請(qǐng)求方法進(jìn)行有效的封裝和優(yōu)化,大大提升代碼的復(fù)用性和開發(fā)效率,從而更好地滿足開發(fā)者對(duì)微信小程序網(wǎng)絡(luò)請(qǐng)求的需求。當(dāng)然,我們需要根據(jù)不同的業(yè)務(wù)場(chǎng)景,不斷地探究可行的解決方案,不斷提高代碼的復(fù)用性和開發(fā)效率。