基于小程序請(qǐng)求接口wx.request封裝的類axios請(qǐng)求
Introduction
- wx.request 的配置、axios 的調(diào)用方式
- 源碼戳我
feature
- 支持 wx.request 所有配置項(xiàng)
- 支持 axios 調(diào)用方式
- 支持 自定義 baseUrl
- 支持 自定義響應(yīng)狀態(tài)碼對(duì)應(yīng) resolve 或 reject 狀態(tài)
- 支持 對(duì)響應(yīng)(resolve/reject)分別做統(tǒng)一的額外處理
- 支持 轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
- 支持 請(qǐng)求緩存(內(nèi)存或本地緩存),可設(shè)置緩存標(biāo)記、過期時(shí)間
use
app.js @onLaunch
import axios form 'axios'
axios.creat({
header: {
content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
baseUrl: 'https://api.baseurl.com',
...
});
page.js
axios
.post("/url", { id: 123 })
.then((res) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
API
axios(config) - 默認(rèn)get
axios(url[, config]) - 默認(rèn)get
axios.get(url[, config])
axios.post(url[, data[, config]])
axios.cache(url[, data[, config]]) - 緩存請(qǐng)求(內(nèi)存)
axios.cache.storage(url[, data[, config]]) - 緩存請(qǐng)求(內(nèi)存 & local storage)
axios.creat(config) - 初始化定制配置,覆蓋默認(rèn)配置
config
默認(rèn)配置項(xiàng)說明
export default {
// 請(qǐng)求接口地址
url: undefined,
// 請(qǐng)求的參數(shù)
data: {},
// 請(qǐng)求的 header
header: "application/json",
// 超時(shí)時(shí)間,單位為毫秒
timeout: undefined,
// HTTP 請(qǐng)求方法
method: "GET",
// 返回的數(shù)據(jù)格式
dataType: "json",
// 響應(yīng)的數(shù)據(jù)類型
responseType: "text",
// 開啟 http2
enableHttp2: false,
// 開啟 quic
enableQuic: false,
// 開啟 cache
enableCache: false,
/** 以上為wx.request的可配置項(xiàng),參考 https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html */
/** 以下為wx.request沒有的新增配置項(xiàng) */
// {String} baseURL` 將自動(dòng)加在 `url` 前面,可以通過設(shè)置一個(gè) `baseURL` 便于傳遞相對(duì) URL
baseUrl: "",
// {Function} (同axios的validateStatus)定義對(duì)于給定的HTTP 響應(yīng)狀態(tài)碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設(shè)置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 reject
validateStatus: undefined,
// {Function} 請(qǐng)求參數(shù)包裹(類似axios的transformRequest),通過它可統(tǒng)一補(bǔ)充請(qǐng)求參數(shù)需要的額外信息(appInfo/pageInfo/場(chǎng)景值...),需return data
transformRequest: undefined,
// {Function} resolve狀態(tài)下響應(yīng)數(shù)據(jù)包裹(類似axios的transformResponse),通過它可統(tǒng)一處理響應(yīng)數(shù)據(jù),需return res
transformResponse: undefined,
// {Function} resolve狀態(tài)包裹,通過它可做接口resolve狀態(tài)的統(tǒng)一處理
resolveWrap: undefined,
// {Function} reject狀態(tài)包裹,通過它可做接口reject狀態(tài)的統(tǒng)一處理
rejectWrap: undefined,
// {Boolean} _config.useCache 是否開啟緩存
useCache: false,
// {String} _config.cacheName 緩存唯一key值,默認(rèn)使用url&data生成
cacheName: undefined,
// {Boolean} _config.cacheStorage 是否開啟本地緩存
cacheStorage: false,
// {Any} _config.cacheLabel 緩存標(biāo)志,請(qǐng)求前會(huì)對(duì)比該標(biāo)志是否變化來決定是否使用緩存,可用useCache替代
cacheLabel: undefined,
// {Number} _config.cacheExpireTime 緩存時(shí)長(zhǎng),計(jì)算緩存過期時(shí)間,單位-秒
cacheExpireTime: undefined,
};
實(shí)現(xiàn)
axios.js
import Axios from "./axios.class.js";
// 創(chuàng)建axios實(shí)例
const axiosInstance = new Axios();
// 獲取基礎(chǔ)請(qǐng)求axios
const { axios } = axiosInstance;
// 將實(shí)例的方法bind到基礎(chǔ)請(qǐng)求axios上,達(dá)到支持請(qǐng)求別名的目的
axios.creat = axiosInstance.creat.bind(axiosInstance);
axios.get = axiosInstance.get.bind(axiosInstance);
axios.post = axiosInstance.post.bind(axiosInstance);
axios.cache = axiosInstance.cache.bind(axiosInstance);
axios.cache.storage = axiosInstance.storage.bind(axiosInstance);
Axios class
初始化
- defaultConfig 默認(rèn)配置,即 defaults.js
- axios.creat 用戶配置覆蓋默認(rèn)配置
- 注意配置初始化后 mergeConfig 不能被污染,config 需通過參數(shù)傳遞
constructor(config = defaults) {
this.defaultConfig = config;
}
creat(_config = {}) {
this.defaultConfig = mergeConfig(this.defaultConfig, _config);
}
請(qǐng)求別名
- axios 兼容 axios(config) 或 axios(url[, config]);
- 別名都只是 config 合并,最終都通過 axios.requst()發(fā)起請(qǐng)求;
axios($1 = {}, $2 = {}) {
let config = $1;
// 兼容axios(url[, config])方式
if (typeof $1 === 'string') {
config = $2;
config.url = $1;
}
return this.request(config);
}
post(url, data = {}, _config = {}) {
const config = {
..._config,
url,
data,
method: 'POST',
};
return this.request(config);
}
請(qǐng)求方法 _request
請(qǐng)求配置預(yù)處理
- 實(shí)現(xiàn) baseUrl
- 實(shí)現(xiàn) transformRequest(轉(zhuǎn)換請(qǐng)求數(shù)據(jù))
_request(_config = {}) {
let config = mergeConfig(this.defaultConfig, _config);
const { baseUrl, url, header, data = {}, transformRequest } = config;
const computedConfig = {
header: {
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
...header,
},
...(baseUrl && {
url: combineUrl(url, baseUrl),
}),
...(transformRequest &&
typeof transformRequest === 'function' && {
data: transformRequest(data),
}),
};
config = mergeConfig(config, computedConfig);
return wxRequest(config);
}
wx.request
發(fā)起請(qǐng)求、處理響應(yīng)
- 實(shí)現(xiàn) validateStatus(狀態(tài)碼映射 resolve)
- 實(shí)現(xiàn) transformResponse(轉(zhuǎn)換響應(yīng)數(shù)據(jù))
- 實(shí)現(xiàn) resolveWrap、rejectWrap(響應(yīng)狀態(tài)處理)
export default function wxRequest(config) {
return new Promise((resolve, reject) => {
wx.request({
...config,
success(res) {
const {
resolveWrap,
rejectWrap,
transformResponse,
validateStatus,
} = config;
if ((validateStatus && validateStatus(res)) || ifSuccess(res)) {
const _resolve = resolveWrap ? resolveWrap(res) : res;
return resolve(
transformResponse ? transformResponse(_resolve) : _resolve
);
}
return reject(rejectWrap ? rejectWrap(res) : res);
},
fail(res) {
const { rejectWrap } = config;
reject(rejectWrap ? rejectWrap(res) : res);
},
});
});
}
請(qǐng)求緩存的實(shí)現(xiàn)
- 默認(rèn)使用內(nèi)存緩存,可配置使用 localStorage
- 封裝了 Storage 與 Buffer 類,與 Map 接口一致:get/set/delete
- 支持緩存標(biāo)記&過期時(shí)間
- 緩存唯一 key 值,默認(rèn)使用 url&data 生成,無需指定
import Buffer from '../utils/cache/Buffer';
import Storage from '../utils/cache/Storage';
import StorageMap from '../utils/cache/StorageMap';
/**
* 請(qǐng)求緩存api,緩存于本地緩存中
*/
storage(url, data = {}, _config = {}) {
const config = {
..._config,
url,
data,
method: 'POST',
cacheStorage: true,
};
return this._cache(config);
}
/**
* 請(qǐng)求緩存
* @param {Object} _config 配置
* @param {Boolean} _config.useCache 是否開啟緩存
* @param {String} _config.cacheName 緩存唯一key值,默認(rèn)使用url&data生成
* @param {Boolean} _config.cacheStorage 是否開啟本地緩存
* @param {Any} _config.cacheLabel 緩存標(biāo)志,請(qǐng)求前會(huì)對(duì)比該標(biāo)志是否變化來決定是否使用緩存,可用useCache替代
* @param {Number} _config.cacheExpireTime 緩存時(shí)長(zhǎng),計(jì)算緩存過期時(shí)間,單位-秒
*/
_cache(_config) {
const {
url = '',
data = {},
useCache = true,
cacheName: _cacheName,
cacheStorage,
cacheLabel,
cacheExpireTime,
} = _config;
const computedCacheName = _cacheName || `${url}#${JSON.stringify(data)}`;
const cacheName = StorageMap.getCacheName(computedCacheName);
// return buffer
if (useCache && Buffer.has(cacheName, cacheLabel)) {
return Buffer.get(cacheName);
}
// return storage
if (useCache && cacheStorage) {
if (Storage.has(cacheName, cacheLabel)) {
const data = Storage.get(cacheName);
// storage => buffer
Buffer.set(
cacheName,
Promise.resolve(data),
cacheExpireTime,
cacheLabel
);
return Promise.resolve(data);
}
}
const curPromise = new Promise((resolve, reject) => {
const handleFunc = (res) => {
// do storage
if (useCache && cacheStorage) {
Storage.set(cacheName, res, cacheExpireTime, cacheLabel);
}
return res;
};
this._request(_config)
.then((res) => {
resolve(handleFunc(res));
})
.catch(reject);
});
// do buffer
Buffer.set(cacheName, curPromise, cacheExpireTime, cacheLabel);
return curPromise;
}
到此這篇關(guān)于基于小程序請(qǐng)求接口wx.request封裝的類axios請(qǐng)求的文章就介紹到這了,更多相關(guān)小程序 wx.request封裝類axios請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Bootstrap 3.x打印預(yù)覽背景色與文字顯示異常的解決
前幾天同事有個(gè)問題咨詢我,他在調(diào)用print()來打印頁(yè)面,發(fā)現(xiàn)打印預(yù)覽頁(yè)面上的背景色無法顯示以及文字總是顯示為黑色,感覺非常奇怪,我通過測(cè)試發(fā)現(xiàn)是Bootstrap的問題,現(xiàn)在將解決的方法分享給大家,希望可以幫助到同樣遇到這個(gè)問題的朋友們,下面來一起看看。2016-11-11
bootstrap-table實(shí)現(xiàn)服務(wù)器分頁(yè)的示例 (spring 后臺(tái))
本篇文章主要介紹了bootstrap-table實(shí)現(xiàn)服務(wù)器分頁(yè)的示例 (spring 后臺(tái)),具有一定的參考價(jià)值,有興趣的可以了解一下2017-09-09
Javascript中的every()與some()的區(qū)別和應(yīng)用小結(jié)
every跟some不同點(diǎn)在于,every要判斷數(shù)組中是否每個(gè)元素都滿足條件,只有都滿足條件才返回true,只要有一個(gè)不滿足就返回false,這篇文章主要介紹了Javascript中的every()與some()的區(qū)別和應(yīng)用,需要的朋友可以參考下2023-05-05
關(guān)于ECharts設(shè)置x軸刻度間隔的兩種方式
這篇文章主要介紹了關(guān)于ECharts設(shè)置x軸刻度間隔的兩種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
微信小程序開發(fā)(二)圖片上傳+服務(wù)端接收詳解
本篇文章主要介紹了微信小程序開發(fā)(二)圖片上傳+服務(wù)端接收,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01
JavaScript前端控制網(wǎng)絡(luò)并發(fā)數(shù)目的常見方法小結(jié)
控制前端發(fā)起請(qǐng)求的并發(fā)數(shù),即限制同一時(shí)間內(nèi)進(jìn)行處理的請(qǐng)求數(shù)量,是一種有效的策略,本文將詳細(xì)介紹前端控制并發(fā)數(shù)的幾種常見做法,希望對(duì)大家有所幫助2023-12-12
使用p5.js實(shí)現(xiàn)動(dòng)態(tài)GIF圖片臨摹重現(xiàn)
這篇文章主要為大家詳細(xì)介紹了使用p5.js實(shí)現(xiàn)動(dòng)態(tài)GIF圖片臨摹重現(xiàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10

