自從Axios成功打入Vue全家桶之后,便開始火的一塌糊涂!截止到目前,其在github上的star即將突破80k!可以說Axios是當下前端界最流行的ajax請求庫,可(jue)能(dui)沒有之一!
即然Axios人氣如此之高,那么閱讀并研究它的源碼也是非常有必要的,因為這樣不僅可以讓自己少走很多彎路,還會對作者多年的編程思想以及經(jīng)驗進行獵取,從中抽象出一些架構(gòu)及模式性的高級內(nèi)容,最終提高自己的實現(xiàn)能力和技巧,讓自己變得更加強大!
(啰嗦句:閱讀源碼的換確確可以提升自身的編碼水平,但需要你擁有一定相關(guān)經(jīng)驗基礎以及相對領域的認知,否則看源碼絕對是在浪費時間!為什么?因為你看不懂!)
本系列文章將會對Axios源碼思想進行精簡提煉,從而將大家所關(guān)心的一些內(nèi)部原理問題進行解答。
一、封裝一個簡易版本的xhr + promise的異步ajax請求庫
由于axios是一個基于xhr + promise的異步ajax請求庫,所以咱們可以先單純的封裝一個:
function axios(config){
// 將請求方式全部轉(zhuǎn)為大寫
const method = (config.method || "get").toUpperCase();
// 返回Promise
return new Promise((resolve,reject)=>{
// 聲明xhr
const xhr = new XMLHttpRequest();
// 定義一個onreadystatechange監(jiān)聽事件
xhr.onreadystatechange = function () {
// 數(shù)據(jù)全部加載完成
if(xhr.readyState === 4){
// 判斷狀態(tài)碼是否正確
if(xhr.status >= 200 && xhr.status < 300){
// 得到響應體的內(nèi)容
const data = JSON.parse(xhr.responseText);
// 得到響應頭
const headers = xhr.getAllResponseHeaders();
// request 即是 xhr
const request = xhr;
// 狀態(tài)碼
const status = xhr.status;
// 狀態(tài)碼的說明
const statusText = xhr.statusText
resolve({
config,
data,
headers,
request,
status,
statusText
});
}else{
reject("請求失敗"+xhr.status+xhr.statusText);
}
}
}
// 判斷是否擁有params,且類型為object
if(typeof config.params === "object"){
// 將object 轉(zhuǎn)為 urlencoded
const arr = Object.keys(config.params);
const arr2 = arr.map(v=>v+"="+config.params[v]);
const url = arr2.join("&");
config.url += "?" + url;
}
xhr.open(method,config.url);
// post put patch
if(method === "POST" || method === "PUT" || method === "PATCH"){
if(typeof config.data === "object")
xhr.setRequestHeader("content-type","application/json");
else if(typeof config.data === "string")
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send(JSON.stringify(config.data));
}else{
xhr.send();
}
})
}
以上代碼實現(xiàn)了axios(config)直接發(fā)起請求,例如:
axios({
method:"delete",
url:"data.json"
}).then(res=>console.log(res))
但是,如果我想通過axios.get(url[, config])、axios.delete(url[, config])、axios.post(url[, data[, config]])等請求方式就行不通了。
二、封裝request
通過閱讀源碼得到一些啟示:源碼中有一個名為Axios的構(gòu)造函數(shù),而我們的xhr + promise封裝在Axios.prototype.request函數(shù)中。另外我們所使用的axios.get、axios.post等也都是定義在Axios.prototype中。
根據(jù)這些啟示將代碼調(diào)整為:
// 構(gòu)造函數(shù)
function Axios(){
}
Axios.prototype.request = function (config) {
// 將請求方式全部轉(zhuǎn)為大寫
const method = (config.method || "get").toUpperCase();
// 返回Promise
return new Promise((resolve,reject)=>{
// 聲明xhr
const xhr = new XMLHttpRequest();
// 定義一個onreadystatechange監(jiān)聽事件
xhr.onreadystatechange = function () {
// 數(shù)據(jù)全部加載完成
if(xhr.readyState === 4){
// 判斷狀態(tài)碼是否正確
if(xhr.status >= 200 && xhr.status < 300){
// 得到響應體的內(nèi)容
const data = JSON.parse(xhr.responseText);
// 得到響應頭
const headers = xhr.getAllResponseHeaders();
// request 即是 xhr
const request = xhr;
// 狀態(tài)碼
const status = xhr.status;
// 狀態(tài)碼的說明
const statusText = xhr.statusText
resolve({
config,
data,
headers,
request,
status,
statusText
});
}else{
reject("請求失敗"+xhr.status+xhr.statusText);
}
}
}
// http://127.0.0.1/two?a=1&b=2
// 判斷是否擁有params,且類型為object
if(typeof config.params === "object"){
// 將object 轉(zhuǎn)為 urlencoded
const arr = Object.keys(config.params);
const arr2 = arr.map(v=>v+"="+config.params[v]);
const url = arr2.join("&");
config.url += "?" + url;
}
xhr.open(method,config.url);
// post put patch
if(method === "POST" || method === "PUT" || method === "PATCH"){
if(typeof config.data === "object")
xhr.setRequestHeader("content-type","application/json");
else if(typeof config.data === "string")
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send(JSON.stringify(config.data));
}else{
xhr.send();
}
})
}
Axios.prototype.get = function (url,config) {
return this.request({
method:"get",
url,
...config
});
}
Axios.prototype.post = function (url,data) {
return this.request({
url,
method:"post",
data
})
}
// 其它請求delete,patch省略
export default new Axios();
這樣我們終于可以通過axios.get(url[, config])、axios.post(url[, data[, config]])請求數(shù)據(jù)了。
import axios from "./Axios.js";
axios.post("data.json",{
a:1,
b:2
}).then(res=>{
console.log(res);
})
axios.get("data.json",{
params:{
a:1,
b:2
}
}).then(res=>{
console.log(res);
})
但是axios(config)又不行了。
三、createInstance函數(shù)
繼續(xù)攻讀源碼發(fā)現(xiàn):axios 本質(zhì)不是Axios構(gòu)造函數(shù)的實例,而是一個函數(shù)名字為createInstance的函數(shù)對象,在該函數(shù)中實例化了Axios。也就是說:我們所使用的axios并不是Axios的實例,而是Axios.prototype.request函數(shù)bind()返回的函數(shù)。
function createInstance(defaultConfig){
const context = new Axios(defaultConfig);
Axios.prototype.request.bind(context);
// instance 是一個函數(shù)。該函數(shù)是request,并且將this指向context.
var instance = Axios.prototype.request.bind(context);// 等同于上面那行代碼
// 將Axios的原型方法放置到instance函數(shù)屬性中
Object.keys(Axios.prototype).forEach(method=>{
instance[method] = Axios.prototype[method].bind(context)
})
Object.keys(context).forEach(attr=>{
instance[attr] = context[attr];
})
return instance;
}
export default createInstance;
四、axios實現(xiàn)多種請求方式原理完整代碼:
// 構(gòu)造函數(shù)
function Axios(){
}
Axios.prototype.request = function (config) {
// 將請求方式全部轉(zhuǎn)為大寫
const method = (config.method || "get").toUpperCase();
// 返回Promise
return new Promise((resolve,reject)=>{
// 聲明xhr
const xhr = new XMLHttpRequest();
// 定義一個onreadystatechange監(jiān)聽事件
xhr.onreadystatechange = function () {
// 數(shù)據(jù)全部加載完成
if(xhr.readyState === 4){
// 判斷狀態(tài)碼是否正確
if(xhr.status >= 200 && xhr.status < 300){
// 得到響應體的內(nèi)容
const data = JSON.parse(xhr.responseText);
// 得到響應頭
const headers = xhr.getAllResponseHeaders();
// request 即是 xhr
const request = xhr;
// 狀態(tài)碼
const status = xhr.status;
// 狀態(tài)碼的說明
const statusText = xhr.statusText
resolve({
config,
data,
headers,
request,
status,
statusText
});
}else{
reject("請求失敗"+xhr.status+xhr.statusText);
}
}
}
// http://127.0.0.1/two?a=1&b=2
// 判斷是否擁有params,且類型為object
if(typeof config.params === "object"){
// 將object 轉(zhuǎn)為 urlencoded
const arr = Object.keys(config.params);
const arr2 = arr.map(v=>v+"="+config.params[v]);
const url = arr2.join("&");
config.url += "?" + url;
}
xhr.open(method,config.url);
// post put patch
if(method === "POST" || method === "PUT" || method === "PATCH"){
if(typeof config.data === "object")
xhr.setRequestHeader("content-type","application/json");
else if(typeof config.data === "string")
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send(JSON.stringify(config.data));
}else{
xhr.send();
}
})
}
Axios.prototype.get = function (url,config) {
return this.request({
method:"get",
url,
...config
});
}
Axios.prototype.post = function (url,data) {
return this.request({
url,
method:"post",
data
})
}
function createInstance(defaultConfig){
const context = new Axios(defaultConfig);
Axios.prototype.request.bind(context);
// instance 是一個函數(shù)。該函數(shù)是request,并且內(nèi)部this指向context.
var instance = Axios.prototype.request.bind(context);// 等同于上面那行代碼
// 將Axios的原型方法放置到instance函數(shù)屬性中
Object.keys(Axios.prototype).forEach(method=>{
instance[method] = Axios.prototype[method].bind(context)
})
Object.keys(context).forEach(attr=>{
instance[attr] = context[attr];
})
return instance;
}
export default createInstance;